pic microcontroller - hadassahcs.hadassah.ac.il/staff/martin/embedded/slide04-1.pdf · embedded...
TRANSCRIPT
1Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
PIC
Microcontroller
2Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
PIC Microcontroller (MCU)Widely used device from Microchip Technology
Sold > 10 billion PIC controllersSeveral device families
Many devices per familyCommon development environment
Widely availableLarge user baseExtensive application notes
Low costFree / low cost development tools
Basic architectural featuresPipelined RISC microprocessor coreAccumulator execution modelData width — 8 / 16 / 32 bitsInstruction width — 12 / 14 / 16 / 32 bits
3Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
PIC Families
Data width8 / 16/ 32 bitsWider integer ⇒ higher precision arithmetic
Instruction width12 / 14 / 16 / 32 bitsWider instruction ⇒ more complex instructions + higher precision arithmetic
Integrated DSP
dsPIC30
PIC24
PIC18
PIC10 / PIC12 / PIC16
Family
14‐bitsMid‐Range
16‐bits
32 bits32 bits32‐bit MCU
16 bits16 bits16‐bit MCU
12‐bits
8 bits
Baseline
8‐bit MCU
Instruction Width
Data Width
Architecture
4Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Typical ApplicationsBaseline
Replace discrete logic functions Gates, simple state machines, encoders/decoders, etc.
Disposable electronics Drug / pregnancy testers, dialysis monitor, etc
Mid-RangeDigital sensors, displays, controllers, telecom equipmentGlucose / blood pressure set
PIC18 Integration with peripherals + networks
USB, Ethernet, MCU-to-MCU, etc
Higher level analog peripherals, industrial control, major appliancesPIC24 / dsPIC30
16-bit ALU with integrated DSPPortable EGK
PIC32General purpose RISC microprocessor + controller
MRI
5Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Learning PIC Architecture
Variety Hundreds of PIC devices in 3 families and several sub-families
Updates Microchip Technology upgrades devices frequentlyFamiliar devices replaced with new model
Instruction Set Architecture 8 and 16 bit devices share approximately uniform instruction setPIC32 implements MIPS ISA
CaveatsCourse 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 titlesEach device is uniqueFew statements are precisely true about each device
Some general observations
6Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
8‐Bit PIC MCUs
8‐bit parallel ports
Synchronous / asynchronous serial ports
Timers + watchdog timer
A/D + D/A converters
Pulse width modulators
I/O devices
Stores 0 (no stack) to 31 instruction addresses
Used for function calls
Stack
Pipelined RISC
33 to 77 instructions
Architecture
Addressable unit = instruction word = 12 / 14 / 16 bits
Smallest: 2 Kword (3 KB of 12‐bit instructions)
Largest: 64 Kword (128 KB of 16‐bit instructions)
Program memory
Organized as 8‐bit registers
Some devices also store data on EEPROM
16 B to 4 KB
Data memory
7Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
8‐Bit PIC Operation ModelALU sources
Special WORKING register W Data register or immediate
ALU destination Data register or W
Transfer operations Data register ↔ W
Status registerFlags produced by ALU operations
ArithmeticLogicUnit(ALU)
DataMemory
Status
Data Bus
W
8Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Pipeline Operation
Branch instructions require 2 instruction cycles
InstructionFetch
InstructionMemory
ExecuteDecode
DataMemory
Address Instruction Address Data
W
1 2 3 4 5 I1 fetch execute I2 fetch execute I3 fetch execute I4 fetch execute
Instruction Cycles
Instruction cycles (CY)
9Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Pipeline Operation
Instruction Cycle4 cycles of external clock (oscillator)CY = Q1 → Q2 → Q3 → Q4
Instruction fetch
Execution
1 2 3 4 5 Q1Q2Q3Q4 Q1Q2Q3Q4 Q1Q2Q3Q4 Q1Q2Q3Q4 Q1Q2Q3Q4I1 fetch execute I2 fetch execute I3 fetch execute I4 fetch execute
Instruction Cycles
Clock cycles (OSC)
Q2 – Q3
IR← [PC]FetchQ4
PC ← PC + 1Update Program PointerQ1
Operation dependentDecode and ExecuteQ1 – Q4
IR — instruction registerPC — program counter
10Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Clock TypesRC oscillator
Least expensive Can be used for non-critical frequency accuracy and stability Some devices have internal RC oscillator at 4 MHz
Crystal oscillatorMost stable
External clockProvided by external digital system
Specific modes LP mode — frequencies between 32 kHz and 200 kHzXT mode — frequencies between 100 kHz and 4 MHzHS mode — frequencies between 8 MHz and 20 MHz
11Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Sleep ModeLow-power mode
Main oscillator stoppedMost MCU functions stoppedWatchdog time continuesPower consumed < 1 mA for some models
Instruction SLEEP MCU → sleep modeData register values stable
Pipeline lockedSleep instruction executes ⇒ next instruction already fetched
On wake upNext instruction executes Recommendation — instruction after sleep = NOPWatchdog timer counter reset
12Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Wake Up EventsReset
Fetch instruction from address 0
Watchdog timer overflowNormal execution of instruction following sleep
Interrupt Interrupt not enabled ⇒ ignore interruptEnabledNormal execution of instruction following sleepPC jumps to address 4 in program memory Finds interrupt routine
13Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Watchdog TimerWDT oscillator (clock)
Independent from main clockContinues in low power modeMay be disabled
WDT timeout Timeout = 18 msNon-sleep mode
MCU resets
Sleep modeMCU wakes up → executes instruction following sleep
Reset WDTCLRWDT resets timeout = 18 ms
PrescalerDivide time-base by 2k, k = 0, ... , 7Extend timeout up to 2300 ms
14Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Some Typical 8‐bit PIC Device Families
Flash Flash Flash Flash Flash ROM
16 – 70 4 – 54 12 – 3264I/O pins
31 levels8 levels2 levels2 levels2 levelsStack
$1.20 ‐ $8.50$0.35 – $2.50 $0.50 – $0.85 $0.50$0.35Bulk price
2 – 5 2 – 3 111Timers
18 – 100 6 – 64 14 – 4086Pins
int / extint / ext000Interrupts
256 – 4K56 – 36825 – 134 25 – 41 16 – 24 Data memory
(bytes)
2 Kwords –64 Kwords
256 – 8192 words
1024 – 2048 words
512 – 1024 words
256 – 512 words
Program memory
8335333333Instructions
16 bits14 bits12 bits12 bits12 bitsInstruction
word
PIC10F3xxPIC12F6xxPIC16F6xx
PIC18F5xxPIC16F5xxPIC12F5xxPIC10F2xx
15Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Typical Baseline MCU —PIC16X5xx Family
12‐bit instruction
General I/O ports
8‐bit data
timer
W+ ALU
16Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Typical Mid‐Range MCU — PIC16F873
14‐bit instruction
General I/O portsExternal Interrupt
8‐bit data
Timers A/D UARTCompare‐Capture‐Pulsewidth (CCP)Synchronous Serial Port (SSP)
17Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Typical PIC18 MCU
16‐bit instruction
8‐bit data
General I/O portsExternal Interrupts
Timers A/D UARTUSBCompare‐Capture‐Pulsewidth (CCP)Controller Area Network (CAN)
18Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Mid‐Range PIC MCUs
19Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Data Memory / RegistersRegister
Addressable location in data memory 8-bit word (byte)
Data address space9 bit address ⇒ memory ≤ 29 = 512 bytes = 0.5 KB
Memory partitioned into banksBank = 27 = 128 = 80h registers (1/8 KB)7 bit file address
Displacement in bank = 00h … 7Fh
Banks in address space≤ 29-7 = 4 banks2 to 4 banks implemented in deviceUnimplemented banks
Read as 0Write as NOP
7 bits2 bits
file addressbank
data address
bank
11100100
00h
7Fh
20Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Special / General Registers GPR
General Purpose RegistersUser program data
SFRSpecial Function Registers Reserved for
Control / configurationPeripheral access Indirect addressingProgram counter
Core SFRs Appear in every bank at
same file address
Typical SFRs
Access to EEPROM and Flash memory
EEADRH, EEDATA, …
Access to A/D converterADRESH, ADRESL, ADCON0, …
Access to serial portTXREG, TXSTA, RCREG, RCSTA, …
Timer0TMR0, OPTION, INTCON, …
Access to parallel portsPORTA, TRISA, …
Components of interrupt handling
INTCON, PIR1, PIE1, PIR2, PIE2
File Select for indirect data addressing
FSR
Components of program counter (PC)
PCLATHPCL
Timer optionsOPTION
Status word + flagsSTATUS
21Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Data Memory MapNotes
(2,3) Not all locations implemented on all devices
(4) Common RAM —accessible in all banks (on applicable devices)
(5) Not implemented on smaller devices
22Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Status Register
xxx11000Reset value
Writable
Name
R/WR/WR/WROROR/WR/WR/W
CDCZPD#T0#RP0RP1IRP
01234567
Direct Register PointerRP1, RP0
Indirect Register PointerBank Select
IRP
C← 1 on carry (Addition) C← 0 on borrow (Subtraction)
DC← 1 on carry (Addition)DC← 0 on borrow (Subtraction)
Z← 1 on ALU zeroZ← 0 on non‐zero
PD#← 0 on SLEEPPD#← 1 on CLRWDT and power‐on reset
TO#← 0 on WDT overflowTO#← 1 on power‐on reset, CLRWDT, SLEEP
Carry outC
Half‐byte carry (bits 3,4)
DC
Zero flagZ
Low‐powerPD#
State of WDTTO#
Core SFR accessible at file address 03h in every bank
23Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Addressing Data Memory
Direct addressing Program specifies data addressBank selection
STATUS bits RP1 and RP0On reset
RP1 = RP0 = 0 ⇒ bank 0 selectedBank switching
Write to STATUS<6:5>
File AddressLiteral field in instruction
RP0 7 bits from instructionRP1
file addressbank
012345678
Concatenation of A and B(A bits followed by B bits)
A.B
Bits a to b in register REGREG<a:b>
Bit b in register REGREG<b>
Notation
24Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Addressing Data MemoryIndirect addressing
Program writes to Special Function Registers (SFRs)Address formed from SFRs
Instructions can increment/decrement SFR valuesSimilar to pointer arithmetic
File Select Register (FSR )Core SFR accessible at file address 08h in all banksFile Address
FSR<6:0>
Bank IRP.FSR<7>STATUS bit IRP (Indirect Register Pointer)
On small devices1 or 2 banks = 128 or 256 bytes of data memory8 bit FSR address covers 2 banksIRP not implemented (read 0 / write = NOP)
8 bits of FSRIRP
file addressbank
012345678
25Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
INDF RegisterINDF
Core SFR accessible at file address 00h in all banksVirtual pointer — not physical registerTracks contents of FSRSimplifies pointer arithmetic
Example In register file,
[05] = 10h[06] = 0Ah
Load FSR ← 05 ; FSR points to file address 05[INDF] = 10h ; INDF points to file address 05FSR++ ; increment FSR ⇒ FSR = 06[INDF] = 0Ah ; INDF points to file address 06
26Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Instruction Memory Space
Instruction addressn bit location addressLocation = instruction≤ 2n instructionsInstruction width
12 / 14 / 16 bits
PagePartition of instruction
memory space2k instructions / pagek bit offset
instruction 1…1 1…11 … … Page
instruction 1…1 0…00 … …
instruction 0…1 1…11 … …
instruction 0…1 0…11 instruction 0…1 0…10 instruction 0…1 0…01
Page1
instruction 0…1 0…00 instruction 0…0 1…11
… … instruction 0…0 0…11 instruction 0…0 0…10 instruction 0…0 0…01
Page0
instruction 0…0 0…00 page offset
Memory Location Address
k bitsn – k bits
offsetpage
n bit address
All 8‐bit MCUs
27Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Instruction Memory SpaceMid-Range instruction memory
14-bit instruction wordn = 13
213 = 8192 instruction wordsk = 11
Page = 211 = 2048 = 800h words
Program counter (PC)PC<12:11> = page number ⇒ 4 pagesPC<10:0> = offset
Reserved addressesAddress 0h
Reset vector — pointer to reset routine Address 4h
Interrupt vector — pointer to interrupt service routine
11 bits2 bits
offsetpage
13 bit PC
0101112
28Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
PC AccessPC register details
PC low (PCL) = PC<7:0>Accessible by instruction reads/writes
PC high (PCH) = PC<12:8>Not directly accessible to instructions
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
PC 0123456789101112
offsetpage
PCLPCH
PCLATH01234
29Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
PC UpdatesReset
PC ← 0
Non-branch instructionPC ← PC + 1
Branch typesDirect branch
GOTO instruction PCH<12:11> ← PCLATH<4:3>
Offset = PC<10:0> ← literal<10:0> from instruction
Indirect branchComputed GOTOWrite to PCL as registerCopies PCL ← ALU resultForces PCH ← PCLATH<4:0>
PC 0123456789101112
offsetpage
PCLPCH
PCLATH01234
012345678910literal
PC 0123456789101112
PCLATH01234
PC 0123456789101112
PCL ← ALU<7:0>PCH
PCLATH01234
30Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Call / ReturnStack
8 level FILO bufferHolds 13 bit instruction addresses on CALL/RETURN
Function entryCALL instruction
STACK ← PC<12:0>
PCL ← literal<10:0> from instructionPCH<12:11> ← PCLATH<4:3>
Function exitRETURN instruction
PC<12:0> ← STACKPCLATH not updated
May be different from PCH after RETURN
012345678910literal
PC 0123456789101112
PCLATH01234
STACKCALL
RETURN
31Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Instruction Format
CALL / GOTOk = 11 bit literal (immediate)
General literalk = 8 bit literal (immediate)
Bit orientedb = bit position in registerf = 7 bit file address
Byte orientedd = 0 ⇒ destination = Wd = 1 ⇒ destination = ff = 7 bit file address
011 1013
kopcode
08 713
kopcode
7 010 6913
fbopcode
08 6713
fdopcode
32Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Instruction SetData transfer
Clear W
Clear f
Move literal to W
Move W to f
d = f
d = W
Move f to d
Comment
ZW ← 0CLRW
Zf ← 0CLRF f
—W ← kMOVLW k
—f ← WMOVWF f
Zf ← fMOVF f, 1MOVF f, fMOVF f
ZW ← fMOVF f, 0 MOVF f, W
Zd ← fMOVF f, d
FlagsOperationMnemonic
destination⎧
= ⎨⎩
W , d =0
f , d = 1
Operands
literalk
destinationd
name / address of registerf
33Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Instruction SetArithmetic and Logic — 1
ZAnd k with WW ← k and WANDLW k
And w with f
Dec f to d
Inc f to d
Sub W from k
Sub W from f
Add k to W
Add w to f
Comment
Zd ← f and WANDWF f, d
Zd ← f – 1DECF f, d
Zd ← f + 1INCF f, d
C, DC, ZW ← k – WSUBLW k
C, DC, Zd ← f – WSUBWF f, d
C, DC, ZW ← k + WADDLW k
C, DC, Zd ← f + WADDWF f, d
FlagsOperationMnemonic
destination⎧
= ⎨⎩
W , d =0
f , d = 1
Operands
literalk
destinationd
name / address of registerf
34Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Instruction SetArithmetic and Logic — 2
—nibble swap
(nibble = half byte)d ← fL ↔ fHSWAPF f, d
compliment f to d
XOR W with k
XOR W with f
OR k with W
OR w with f
Comment
Cd ← #f (not f)COMF f, d
Cd ← right rotate f,CRRF f, d
Cd ← left rotate f,CRLF f, d
ZW ← k xor WXORLW k
Zd ← f xor WXORWF f, d
ZW ← k or WIORLW k
Zd ← f or WIORWF f, d
FlagsOperationMnemonic
destination⎧
= ⎨⎩
W , d =0
f , d = 1
Operands
literalk
destinationd
name / address of registerf
35Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Instruction SetControl
return from subroutine with k in WRETLW k
interrupt returnRETFIE
subroutine returnRETURN
call subroutine in address aCALL a
d ← f - 1, skip one if result = 0DECFSZ f, d
d ← f + 1, skip one if result = 0INCFSZ f, d
skip one instruction if f<b> = 1BTFSS f, b
skip one instruction if f<b> = 0BTFSC f, b
branch to addressGOTO a
OperationMnemonic
bit location
11 bit address
b
a
Operands
literalk
destinationd
name / address of registerf
36Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Instruction SetOther
TO#, PD#
TO#, PD#
—
—
—
Flags
go to low power consumptionSLEEP
WDT ← 0CLRWDT
no operation NOP
f<b> ← 1 BSF f, b
f<b> ← 0 BCF f, b
OperationMnemonic
Operands
bit locationb
name / address of registerf
37Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
CLRF STATUS ; STATUS ← 0MOVLW 0x20 ; W ← 1st address in GPR bank 0MOVWF FSR ; Indirect address register ← W
Bank0_LP
CLRF INDF0 ; address in GPR ← 0INCF FSR ; FSR++ (next GPR address)
BTFSS FSR, 7 ; skip if (FSR<7> == 1) ⇒ FSR = 80hGOTO Bank0_LP ; continue
; ** IF DEVICE HAS BANK1 **
MOVLW 0xA0 ; W ← 1st address in GPR bank 1MOVWF FSR ; Indirect address register ← W
Bank1_LP
CLRF INDF0 ; address in GPR ← 0INCF FSR ; FSR++ (next GPR address)
BTFSS STATUS, C ; skip if (STATUS<0> == 1) ⇒ FSR = 00hGOTO Bank1_LP ; continue
Sample Program FragmentsRAM Initialization
38Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Sample Program Fragments
Prog:movlw HIGH Prog10 ; W ← Prog10<15:8>
; operator HIGH reads bits <15:8> of pointermovwf PCLATH ; PCLATH ← Wgoto Prog10 ; PC<10:0> ← Prog10<7:0>
; PC<12:11> ← PCLATH<4:3>
Prog10:;; Prog10 labels some address in program memory;
Branch to address in new page
39Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Sample Program Fragments
movlw HIGH Prog20 ; W ← Prog10<15:8>movwf PCLATH ; PCLATH ← Wmovlw LOW Prog20 ; W ← Prog10<7:0>movwf PCL ; PCL ← Prog10<7:0>
; PCH ← PCLATH<4:0> Prog20:;; Prog10 labels some address in program memory;
Computed goto
40Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Sample Programs Fragments
btfss f,b ; skip one instruction if; bit b in register f = 1
goto Action2Action1:; instructions for Action1goto Action3Action2:; instructions for Action2Action3:; instructions for Action3
if‐else branch
41Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Sample Programs Fragments
movlw times ; W ← timesmovwf COUNTER ; COUNTER ← W (times)
Loop:;; loop instructions;decfsz COUNTER, f ; COUNTER--
; COUNTER = 0 ⇒ skip nextinstruction
goto Loop ; next iterationEnd:;;
Static loop
42Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Sample Programs Fragments
; Function call returns data at Table.INDEXmovlw HIGH Table ; W ← Table<15:8>movwf PCLATH ; PCLATH ← Wmovf INDEX, W ; W ← INDEXcall Table ; Call to subroutine table;Table:addwf PCL, f ; PCL ← PCL + W = PCL + INDEX
; computed gotoretlw 'A' ; return with W ← 'A' retlw 'B'retlw 'C'retlw 'D'retlw 'E'
Data table in instruction memory
43Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
PIC MCU and the Outside WorldOscillator
Generates device clockFour device clock periods per instruction cycle
PortsData I/O pins
Electrical connections to external circuits
Configured to function as Digital I/O Analog inputs to A/D converter
Peripheral ModulesShare data pins with general ports
Samples analog level → converts to digital representationA/D
Capture/Compare/PWM (Pulse Width Modulation)CCP
Bit-parallel ↔ bit-serial converter for communications
Samples 2 analog levels → outputs bit (A1 > A2)
Counts clock cycles → interrupt on preset count
USART
Comparator
Timer
PICOSC
Ports
Controls
ControlsDevice dependentPower + groundInterrupt (INT)External clock
44Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Configurable Oscillator ModesQuartz crystal time base
Crystal connected between PIC pins OSC1 and OSC2Vibrates in electric field → piezoelectric resonance in voltageModes
LP Low Frequency / Low Power Crystal — 32 kHz to 200 kHzXT Crystal/Resonator — 100 kHz to 4 MHzHS High Speed Crystal/Resonator — 8 MHz to 20 MHz
Resistor/Capacitor time baseCapacitor discharges through resistor in time = 2πRCOscillator frequency f = 1 / (2πRC)Modes
EXTRC — External RC connected between PIC pin OSC1 and groundINTRC — Internal 4 MHz RCCLKOUT
EXTRC or INTRC with instruction clock (= f/4) output on OSC2
45Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Interrupts Interrupt
Instruction at current PC executes Instruction at current PC+1 fetchedStack ← PC+2PC ← interrupt pointerOn return from interrupt PC ← stack
Interrupt sourcesExternal interrupt pin
Pin RB0 on some PIC devices (separate pin on other devices)
Peripheral modulesGeneral internal interruptA/DTimerComparatorUSARTCCP
46Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Interrupt Control RegisterInterrupt Control Register (INTCON)
01234567
RBIFINTFT0IFRBIEINTET0IEPEIEGIE
1 = At least one of RB7:RB4 pins changed state0 = None of RB7:RB4 pins have changed state
1 = INT external interrupt occurred0 = INT external interrupt did not occur
1 = TMR0 register has overflowed0 = TMR0 register did not overflow
1 = Enables RB port change interrupt0 = Disables RB port change interrupt
1 = Enables INT external interrupt0 = Disables INT external interrupt
1 = Enables TMR0 overflow interrupt0 = Disables TMR0 overflow interrupt
1 = Enables all un‐masked peripheral interrupts0 = Disables all peripheral interrupts
1 = Enables all un‐masked interrupts0 = Disables all interrupts
RB Port Change Interrupt FlagRBIF
External Interrupt FlagINTF
Overflow Interrupt FlagT0IF
RB Port Change Interrupt EnableRBIE
External Interrupt EnableINTE
Overflow Interrupt EnableT0IE
Peripheral Interrupt EnablePEIE
Global Interrupt EnableGIE
47Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Peripheral Interrupt Enable (PIE)Number of PIE registers device dependent
ComparatorCMIE
LCD LCDIE
EE Write Complete EEIE
Parallel Slave Port Read/Write PSPIE
Slope A/D TMR Overflow OVFIE
Slope A/D Converter Comparator Trip ADCIE
A/D Converter ADIE
USART Transmit TXIE
USART Receive RCIE
Synchronous Serial Port SSPIE
CCP2 CCP2IE
CCP1 CCP1IE
TMR2 to PR2 Match TMR2IE
TMR1 Overflow TMR1IE
1 = enable device interrupt0 = disable device interrupt
48Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Peripheral Interrupt Register (PIR) — 1Number of PIR registers device dependent
1 = Transmission/reception complete
0 = Waiting to transmit/receive
SSPIE
1 = USART receive buffer RCREG full
0 = USART receive buffer is empty
RCIE
Same as CCP1IECCP2IE
CCP1 Interrupt Flag bit
Capture Mode1 = TMR1 register capture occurred
0 = No TMR1 register capture occurred
Compare Mode1 = A TMR1 register compare match occurred
0 = No TMR1 register compare match occurred
PWM Mode
Unused in this mode
CCP1IE
Same as TMR1IETMR2IE
1 = TMR1 register overflowed
0 = TMR1 register did not overflow
TMR1IE
49Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Peripheral Interrupt Register (PIR) — 2Number of PIR registers device dependent
1 = Comparator input changed
0 = Comparator input not changed
CMIE
1 = LCD interrupt occurred
0 = LCD interrupt did not occur
LCDIE
1 = Data EEPROM write operation complete
0 = Data EEPROM write operation not complete
EEIE
1 = Read or write operation occurred
0 = Read or write did not occur
PSPIE
1 = Slope A/D TMR overflow
0 = Slope A/D TMR did not overflow
OVFIE
1 = A/D conversion complete
0 = A/D conversion not complete
ADCIE
1 = A/D conversion complete
0 = A/D conversion not complete
ADIE
1 = USART transmit buffer TXREG empty
0 = USART transmit buffer is full
TXIE
50Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Interrupt LatencyOn interrupt
1. Current instruction execution completes 2. Current instruction fetch completes 3. PC ← interrupt pointerLatency ~ 3 to 4 instruction cycles
1 2 3
51Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Interrupt Initialization + EnablingPIE1_MASK1 EQU B‘01101010’ ; Interrupt Enable
; Register mask (device; dependent)
;;CLRF STATUS ; Bank0CLRF INTCON ; Disable interrupts during
; configurationCLRF PIR1 ; Clear flagsBSF STATUS, RP0 ; Bank1MOVLW PIE1_MASK1 ; set PIE1 via WMOVWF PIE1BCF STATUS, RP0 ; Bank0BSF INTCON, GIE ; Enable Interrupts
52Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Macros for Register Save / RestorePUSH_MACRO MACRO ; Save register contentsMOVWF W_TEMP ; Temporary register ← WSWAPF STATUS,W ; W ← swap STATUS nibblesMOVWF STATUS_TEMP ; Temporary register ← STATUS
ENDM ; End this Macro
POP_MACRO MACRO ; Restore register contentsSWAPF STATUS_TEMP,W ; W ← swap STATUSMOVWF STATUS ; STATUS ← WSWAPF W_TEMP,F ; W_Temp ← swap W_TempSWAPF W_TEMP,W ; W ← swap W_Temp s
; no affect on STATUSENDM ; End this Macro
53Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Typical Interrupt Service Routine (ISR) — 1org ISR_ADDR ; store at ISR address
PUSH_MACRO ; save context registers W, STATUS
CLRF STATUS ; Bank0
; 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
54Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Typical Interrupt Service Routine (ISR) — 2T1_INT ; Timer1 overflow routine
:BCF PIR1, TMR1IF ; Clear Timer1 overflow interrupt flagGOTO END_ISR ; Leave ISR
AD_INT ; Routine when A/D completes:BCF PIR1, ADIF ; Clear A/D interrupt flagGOTO END_ISR ; Leave ISR
LCD_INT ; LCD Frame routine: BCF PIR1, LCDIF ; Clear LCD interrupt flagGOTO END_ISR ; Leave ISR
PORTB_INT ; PortB change routine:
END_ISR ; Leave ISRPOP_MACRO ; Restore registersRETFIE ; Return and enable interrupts
55Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
TimersWatchdog timer (WDT)
Normal program resets timer before timeout (18 ms)Timeout
Non-sleep mode — MCU resetsSleep mode — MCU wakes up → executes instruction following sleep
Configured in OPTION_REG SFRTimer0
Generic programmable 8-bit timer/counterShares prescaler (divide by 2k, k = 0,...,8) with WDTConfigured in OPTION_REG SFR
Timer1Generic programmable 16-bit timer/counter Read / write two 8-bit registers
Timer2Generic programmable 8-bit timer/counterTime base for PWM mode
56Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Watchdog Timer (WDT)Time base
Internal RC oscillator Timer0 clock source
57Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
OPTION_REG SFR (File Address 081h)
01234567
PS0PS1PS2PSAT0SET0CSINTEDGRBPU
1 = Prescaler is assigned to the WDT (watchdog)0 = Prescaler is assigned to the Timer0 module
1 = Increment on high‐to‐low transition on T0CKI pin
0 = Increment on low‐to‐high transition on T0CKI pin
1 = Transition on T0CKI pin
0 = Internal instruction cycle clock (CLKOUT)
1 = Interrupt on rising edge of INT pin
0 = Interrupt on falling edge of INT pin
1 = Weak pull‐ups are disabled
0 = Weak pull‐ups are enabled by port latch values
Underline— active = 0 / inactive = 1
Prescaler Rate SelectPS2:PS0
Prescaler AssignmentPSA
TMR0 Source Edge SelectT0SE
TMR0 Clock Source SelectT0CS
Interrupt Edge SelectINTEDG
Weak Pull‐up EnableRBPU
WDT
1:1
1:2
1:4
1:8
TMR0
1:2
1:4
1:8
1:16
PS2:PS0
000
001
010
011
WDT
1:16
1:32
1:64
1:128
TMR0
1:32
1:64
1:128 1:256
PS2:PS0
100
101
110 111
58Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Timer08-bit timer/counter
Readable / writable at TMR0 SFR (File Address 081h)8-bit software programmable prescaler
Divide input pulse train (slows time scale)Scale by 1:1 , 1:2, 1:4, ... , 1:128
Selectable clock source External / internal
Interrupt on overflow FFh → 00h
Edge select (phase synchronization with external clock)
59Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Timer0 OperationTimer mode
T0CS = 0TMR0++ on every instruction cycle (without prescaler)Write to TMR0 register ⇒ no increment for two instruction cycles
Counter mode T0CS = 1TMR0++ on every rising or falling edge of T0CKI (external clock)
Edge determined by T0SE bit
Prescaler Set by PSA control bits
TMR0 InterruptGenerated on overflow FFh → 00hSets bit T0IF (INTCON<2>)Timer0 interrupt service routine
Clear T0IF Re-enable interrupt
60Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Initialize Timer0 with Internal Clock SourceCLRF 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 ; Interrupt on rising edge of RB0
; Timer0 increment from internal clock
; Prescale = 1:16.
BCF STATUS, RP0 ; Bank0
T0_OVFL_WAIT
BTFSS INTCON, T0IF ; poll overflow bit
GOTO T0_OVFL_WAIT ; on timer overflow
61Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Timer116-bit timer/counter
TMR1 pair TMR1H:TMR1LReadable and writable 8-bit registers
Counter 0000h to FFFFh with rollover to 0000hGenerate Timer1 interrupt on rollover (if enabled)
ModesSynchronous timer
TMR1++ on every instruction cycle (FOSC / 4)
Asynchronous counterTMR1++ on rising edge of input pin
Synchronous counter TMR1++ on rising edge of sampled input pinSynchronized to internal clock TOSC
Sample input pin on rising edge of TOSC
Input must be high / low for at least 2TOSC
Input
SampleClock
SampledInput
62Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
T1CON SFR
01234567
TMR1ONTMR1CST1SYNCT1OSCENT1CKPS0T1CKPS1
01 = 1:2 Prescale value
00 = 1:1 Prescale value
1 = Enables Timer1
0 = Stops Timer1
1 = Counter Mode (count external clock)
0 = Timer Mode (count internal clock FOSC / 4)
TMR1CS = 1 (Counter Mode)
1 = Asynchronous Counter Mode
0 = Synchronous Counter Mode
TMR1CS = 0 (Timer Mode)
Ignored
1 = Oscillator mode enabled
0 = Oscillator mode disabled
11 = 1:8 Prescale value
10 = 1:4 Prescale value
Timer1 OnTMR1ON
Timer1 Clock Source Select
TMR1CS
Timer1 External Clock Input Synchronization Select
T1SYNC
Timer1 Oscillator EnableT1OSCEN
Timer1 Input Clock Prescale Select
T1CKPS1T1CKPS0
63Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Timer1 Operation
Timer Mode
Counter Mode
Oscillator Mode ⇒ T1CKI ← T1OSI
Sampling
CLK In / OSC out
Async Input
64Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Reading Timer1; All interrupts disabled
MOVF TMR1H, W ; W ← high byteMOVWF TMPH ; TMPH ← WMOVF TMR1L, W ; W ← low byteMOVWF TMPL ; TMPL ← W
; TMR1L can roll-over between reads of high and low bytesMOVF TMR1H, W ; W ← high byte againSUBWF TMPH, W ; Verify high byteBTFSC STATUS,Z ; bad read (Z = 0 ⇒ not equal) ⇒ re-doGOTO CONTINUE
; New reading ⇒ good value.MOVF TMR1H, W ; W ← high byteMOVWF TMPH ; TMPH ← WMOVF TMR1L, W ; W ← low byteMOVWF TMPL ; TMPL ← W; Re-enable interrupts (if required)
CONTINUE; Continue
65Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Writing Timer1
; 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
; Re-enable interrupts (if required)
CONTINUE
; Continue
66Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Timer2Readable / writable 8-bit timer
PrescalerPeriod register PR2
Readable / writable TMR2 = PR2 ⇒ reset (TMR2 ← 0)
Postscaler Counts TMR2 = PR2 resets Triggers TMR2IF interrupt flag
67Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
T2CON SFR
01234567
T2CKPS0T2CKPS1TMR2ONTOUTPS0TOUTPS1TOUTPS2TOUTPS3
00 = Prescaler is 1
01 = Prescaler is 4
1x = Prescaler is 16
1 = Timer2 is on
0 = Timer2 is off
0000 = 1:1 Postscale
0001 = 1:2 Postscale
0010 = 1:3 Postscale
0011 = 1:4 Postscale
:
1111 = 1:16 Postscale
Timer2 Clock Prescale Select
T2CKPS1:0
Timer2 OnTMR2ON
Timer2 OutputPostscale Select
TOUTPS3:0
68Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
PortsI/O pins
Electrical connections to external circuits
Configurable in SFR ADCON1 as
Digital I/O Analog inputs to A/D converter
Mid-Range PIC configurationsMinimal — Port A (6 pins) + Port B (8 pins)Maximal — Port A (6 pins), Port B (8 pins), ... , Port G (8 pins)
Special Function RegistersData
PORTA , ... , PORTGPORTi<x> = data bit on pin x of port i
DirectionTRISA, ... , TRISG
TRISi<x> = 1 ⇒ pin x of port i is Input TRISi<x> = 0 ⇒ pin x of port i is Output
PICOSC
Ports
Controls
69Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Port AccessOutput
Set TRISi<x> = 0Write data bit to PORTi<x>
InputSet TRISi<x> = 1Read data bit from PORTi<x>
Order of operationsRead
Reads levels on physical I/O pins (not data register file)
WriteImplemented as read → modifyCauses update of all input data registers from physical I/O pinsProgram must read all required inputs before any write
70Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
PORTA5 general purpose I/O pins
RA5 and RA3:RA0Standard electrical behavior
TTL input levels and CMOS output drivers
Special input RA4
Schmitt trigger inputThreshold decision converts input to binary (RA4 > threshold)
Open drain outputPermits specialize electrical functions on outputWired-OR, analog weighting, ...
71Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Initializing PORTACLRF STATUS ; Bank0CLRF PORTA ; Initialize PORTABSF STATUS, RP0 ; Select Bank1MOVLW 0xCF ; Initialize data directions
; CFh = 11001111; = x x Out Out In In In In
MOVWF TRISA ; PORTA<3:0> = inputs ; PORTA<5:4> = outputs; TRISA<7:6> always read 0
72Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
PORTB8 general purpose I/O pins
RB7:RB0
Standard electrical behavior TTL input levels and CMOS output drivers
Interrupt on changeInput pins RB7:RB4Inputs compared with previous read of PORTBOR(compare bits) = 1 → RB Port Change Interrupt Can wake device from SLEEP
Example — wake-up on key press
Clear interruptRead or write PORTBClear flag bit RBIF
73Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Ports C to GPorts C to E
8 binary I/O pinsRi7:Ri0, i = C, D, E
Schmitt trigger on each input pin
Ports F and GRi7:Ri0, i = F, G
8 binary inputsSchmitt trigger on each input
8 LCD driver outputsDirect connection to 7-segment display
74Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Analog‐to‐Digital (A/D) Converter ModuleConverts analog input signals
Sample and hold One of 8 analog inputs (channels)Conversion to 8-bit binary number
Analog reference voltage Software selectable
Device supply voltageVoltage level on VREF pin
Can operate in sleep mode
Three registersA/D Result Register (ADRES)A/D Control Register0 (ADCON0)A/D Control Register1 (ADCON1)
75Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
ADCON0 SFR
01234567
ADONResvGO/DONECHS0CHS1CHS2ADCS0ADCS1
0 = deactivated 1 = activated
0 = not in progress
A/D Conversion Status
011 = channel 3 (AN3)
:
111 = channel 7 (AN7)
Analog Channel Select
10 = fOSC/32
11 = fRC (internal A/D RC osc)
A/D Conversion Clock Select
A/D OnADON
0Reserved
1 = in progressGO/DONE
000 = channel 0 (AN0)
001 = channel 1 (AN1)
010 = channel 2 (AN2)
CHS2:CHS0
00 = fOSC/2
01 = fOSC/8
ADCS1:ADCS0
76Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
ADCON1 SFR
01234567
PCFG0PCFG1PCFG2
DD D D D D D D 11x
A A D VREFD D D D 101
A A D A D D D D 100
A A A VREFA A D D 011
A A A A A D D D 010
AA A VREFA A A A 001
A A A A A A A A 000
AN0AN1 AN2 AN3 AN4 AN5 AN6 AN7 PCFG2:PCFG0
Conversion compares to reference voltage VREF = device supply voltageAN3 = D
Conversion compares to reference voltage VREF = voltage on AN3 AN3 = VREF
Port pin configured for digital I/OD
Port pin configured for analog inputA
77Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Operation of A/D ConverterConfigure A/D module
Analog pins + voltage reference + digital I/O in ADCON1Select A/D input channel (ADCON0)Select A/D conversion clock (ADCON0)Activate A/D module (ADCON0)
Configure A/D interrupt (optional)Clear ADIFSet ADIE + GIE
Start conversionSet GO/DONE bit (ADCON0)
Wait for A/D conversion to completePoll GO/DONE until cleared or wait for A/D interrupt
Read resultA/D Result register (ADRES)
Repeat
78Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
A/D ConversionBSF STATUS, RP0 ; Bank1CLRF ADCON1 ; Configure inputs as analogBSF PIE1, ADIE ; Enable A/D interruptsBCF STATUS, RP0 ; Bank0MOVLW 0xC1 ; C1h = 11000001MOVWF ADCON0 ; Internal RC, A/D active, Channel 0BCF PIR1, ADIF ; Clear A/D interrupt flagBSF INTCON, PEIE ; Enable peripheral interruptsBSF 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
79Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Comparator Two analog comparators
Inputs shared with I/O pinsAccess via CMCON SRF (device-dependent file address)
Operation Analog input at VIN+ < VIN– ⇒ output = binary 0Analog input at VIN+ > VIN– ⇒ output = binary 1
CMCON SFR
response time
01234567
CM0CM1CM2CISC1OUTC2OUT
See table on following slidesComparator Input Switch
CISCM2:CM0
1 = VIN+ > VIN–0 = VIN+ > VIN–
Comparator Outputs
C2OUTC1OUT
80Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Comparator Modes — 1
81Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Comparator Modes — 2
82Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Initialize ComparatorFLAG_REG EQU 0x20 ; FLAG_REG points to address 20h
CLRF FLAG_REG ; flag register ← 0CLRF PORTA ; PORTA ← 0ANDLW 0xC0 ; Mask comparator bits W<5:0> ← 0IORWF FLAG_REG,F ; FLAG_REG ← FLAG_REG OR WMOVLW 0x03 ; Init comparator modeMOVWF CMCON ; CM<2:0> = 011 (2 common reference)BSF STATUS,RP0 ; Bank1MOVLW 0x07 ; Initialize data directionMOVWF TRISA ; Set RA<2:0> as inputs
; RA<4:3> as outputs; TRISA<7:5> read 0
BCF STATUS,RP0 ; Bank0CALL DELAY 10 ; 10ms delayMOVF CMCON,F ; Read CMCON (enter read mode)BCF PIR1,CMIF ; Clear pending interruptsBSF STATUS,RP0 ; Bank1BSF PIE1,CMIE ; Enable comparator interruptsBCF STATUS,RP0 ; Bank0BSF INTCON,PEIE ; Enable peripheral interruptsBSF INTCON,GIE ; Global interrupt enable
83Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
USARTUniversal Synchronous / Asynchronous Receiver / Transmitter
Serial Communications Interface (SCI)PC serial port / modem
TransmitParallel → serialData byte as 8 serial bits
Receive Serial → parallelAssemble 8 bits as data byte
ModesAsynchronous
Full duplex — simultaneous transmit + receive
SynchronousHalf duplex — transmit or receiveMaster — synchronize data to internal clock Slave — synchronize data to external clock
84Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
USART Transmit OperationData
Byte → TXREG → framing TSR → bit FIFO → TX pinFraming — add start bit / parity bit
TSR full / empty Port Enable
Parity bitTransmit Speed
Interrupt on empty TXREG
85Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
USART Receive OperationData
RX pin → bit FIFO → RSR → RCREG → byte Framing
Identify data between stop bitsCheck for parity error
Port Enable
Sample + FIFO
RCREG full
Parity bit
Overrun Error Framing ErrorContinuous Receive Enable
86Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
SFRsCCP control register (CPCON)CCPR High byte / Low byte (CCPRH / CCPRL)
I/O pinCPP pin (CPPx) — device-dependent pin configured in TRIS SFR
Capture ModeCaptures 16-bit value of register TMR1 on CCPx event
Every falling edge / rising edge / 4th rising edge / 16th rising edge
Triggers interruptCompare mode
Compare 16-bit (CCPR == TMR1)Configurable response on match
CCPx ← 0 / 1Interrupt with no change on CPPx
Pulse Width Modulation (PWM) modeGenerates duty cycle waveform on CCPx
Capture / Compare / PWM (CCP) Module
Period
Duty cycle
87Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
CCPxCON SFR
01234567
CCPxM0CCPxM1CCPxM2CCPxM3DCxB0DCxB1
0000 = Capture/Compare/PWM off (resets CCPx module)
0100 = Capture mode, every falling edge
0101 = Capture mode, every rising edge
0110 = Capture mode, every 4th rising edge
0111 = Capture mode, every 16th rising edge
1000 = Compare mode, CCP low to high
1001 = Compare mode, CCP high to low
1010 = Compare mode, software interrupt on match
1011 = Compare mode, Trigger special event
11xx = PWM mode
DCx1:DCx0 of 10‐bit PWM duty cycle
DCx9:DCx2 in CCPRxL
CCPx Mode Select bits
CCPxM3:CCPxM0
PWM Duty Cycle bit1 and bit0
DCxB1:DCxB0
88Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Capture ModeEvent
Input pin CCPx divided by prescaler sampled on rising / falling edge
Configuration CCP control register, x = 1, 2
16‐bit value in Timer1
CCPxR = CCPRxH:CCPRxL , x = 1, 2
Interrupt flag , x = 1, 2
89Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Compare Mode16-bit compare
(CCPRx == TMR1), x = 1, 2
16‐bit value of Timer1
16‐bit preset value in CCPRx
Interrupt
Reset Timer1
90Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Pulse Width Modulation (PWM) modeGenerates duty cycle waveform
Period
Duty cycle
Period = (PR2 + 1) × 4 × prescale × TOSCDuty cycle = DC × prescale × TOSC
Set period
Set duty cycle
0 ≤ PR2 ≤ 2550 ≤ DC ≤ 1023
91Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Duty Cycle
PWM OSCT 4 (PR2 1) P T= +× × ×
ON OSCT DC P T= × ×
PWM OSCΔT 4 P T= × ×
ON OSCΔT P T= ×
( ) ( )
( )
( ) ( )
( ) ( ) ( )( )( )
ON OSC
PWM OSC
ON
PWM
ON OSC
PWM OSC
r ON
OSC
T DC P T DCT 4 PR2 1 P T 4 PR2 1
T1 DC 4 PR2 1
T
ΔT P T 1T 4 PR2 1 P T 4 PR2 1
log 4 PR2 1 PTDC 4 PR2 1 2 4 PR2 1 P r
T log 2
× ×= =
× + × × × +
≤ ⇒ ≤ × +
×= =
× + × × × +
× + ×≤ × + ⇒ = ≤ × + × ⇒ =
Duty Cycle
Controllability
Resolution
92Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Duty Cycle Example
( )
( )
( )( )
-
-
1
OSC OSC
PWM
1
PWM
ON
ON
PWM
ON
PWM
r ON
OSC
f 20 MHz T 20 MHz 50 ns
P 1
PR2 63 T 4 64 50 ns 12.8 s
f 12.8 s 78.125 kHz
DC 32 T 32 50 ns 1.6 ms
T 320.125 12.5%
T 4 64
ΔT 1 10.00390625
T 4 64 256
log 256T2 4 64 r 8
T log 2
= ⇒ = =
== ⇒ = × × = μ
= μ =
= ⇒ = × =
= = =×
= = =×
= ≤ × ⇒ = =
Frequency and duty cycle from given parameters
93Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
PWM Example
Internal oscillator fOSC = 4 MHz ⇒ TOSC = 0.25 μs
PWM frequency
TPWM = 1 ms = 4 × (PR2 + 1) × P × 0.25 μs = (PR2 + 1) × P × 1 μsRequire (PR2 + 1) × P = 1000
Preset and PR2
P = 4 ⇒ PR2 + 1 = 250 ⇒ PR2 = 249 = 0xF9
ΔTON = P × TOSC = 1 μs
Duty cycle = 10%
TON = 0.10 × 1 ms = 100 μsDC = 0.10 × 4 × (PR2 + 1) = 100 = 0x064 ⇒ DCH = 0x19 = 25 DCL = 0
Choosing parameters
Oscillator frequency = 4 MHzProduce output with
1 kHz frequency (TPWM = 1 ms)10% duty cycle
94Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
PWM ExampleCode List p = 16F873 include "P16F873.INC" Init_pwm: movlw 0x01 ; Stop Timer2 movwf T2CON ; Prescaler ← 4 clrf CCP1CON ; Reset module CCP1 clrf TMR2 ; Timer2 ← 0 movlw .25 ; 10% duty cycle movwf CCPR1L ; DC1B9:DC1B2 bsf STATUS, RP0 ; Bank 1 movlw .249 ; Timer2 movwf PR2 bcf PIE1, TMR2IE ; Disable Timer2 interrupt bcf PIE1, CCP1IE ; Disable CCP1 interrupt bcf TRISC, 2 ; Pin CCP1 = output bcf STATUS, RP0 ; Bank 0 clrf PIR1 ; Clear interrupt flags movlw 0x0C ; CCP1 in PWM mode movwf CCP1CON ; DC1B1:DC1B0 ← 0 bsf T2CON, TMR2ON ; Start Timer2 return TON_pwm: movwf CCPR1L ; Call to change return ; Duty cycle end
95Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
Data EEPROMAdditional long term data memory
Internal EEPROMIndirect addressing
Not directly mapped in register file spaceAccess through SFRs
EECON1
Control bitsEECON2
Initiates read / write operationVirtual register — not physically implemented
EEDATA
8-bit data for read / writeEEADR
Access address in EEPROM8-bit address ⇒ 256 EEPROM locations
96Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
EECON1 SFR
01234567
RDWRWRENWRERREEIF
1 = Initiates write cycle 0 = Write cycle to data EEPROM is complete (cleared by hardware)
Write ControlWR
1 = Initiates read0 = Does not initiate an EEPROM read (cleared by hardware)
Read ControlRD
1 = Allows write cycles0 = Inhibits write to data EEPROM
1 = Write operation prematurely terminated0 = Write operation completed
1 = Write operation completed0 = Write operation not complete / not started
Write EnableWREN
Error FlagWRERR
Write Operation Interrupt Flag
EEIF
97Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
EECON2 SFRNot physical register
Read EECON2 → 0
SFR access to EEPROM write hardware
Data EEPROM write sequenceEEDATA ← dataEEADR ← address_for_writeW ← 55hEECON2 ← WW ← AAhEECON2 ← W ; EECON2 ← 55AAhEECON1<WR> ← 1 ; initiate (write control bit set)
98Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
EEPROM Read / Write / Verify — 1Read
BCF STATUS, RP0 ; Bank0MOVLW CONFIG_ADDR ; Address in Data EEPROMMOVWF EEADR ; Set read addressBSF STATUS, RP0 ; Set Bank1BSF EECON1, RD ; Initiate EEPROM ReadBCF STATUS, RP0 ; Set Bank0
MOVF EEDATA, W ; W ← EEDATAWrite
BSF STATUS, RP0 ; Bank1BCF INTCON, GIE ; Disable INTsBSF EECON1, WREN ; Enable writeMOVLW 55h ; W ← 55hMOVWF EECON2 ; EECON2 ← WMOVLW AAh ; W ← AAhMOVWF EECON2 ; EECON2 ← WBSF EECON1,WR ; Set WR bit (initiates write)BSF INTCON, GIE ; Enable INTs
99Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
EEPROM Read / Write / Verify — 2Verify
BCF STATUS, RP0 ; Bank0MOVF EEDATA, W ; copy write request data to WBSF STATUS, RP0 ; Bank1
READBSF EECON1, RD ; Initiate readBCF STATUS, RP0 ; Bank0
SUBWF EEDATA, W ; W ← write request – read BTFSS STATUS, Z ; Skip next if (Z == 1)GOTO WRITE_ERR ; Handle write error
100Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
PIC Configuration Bits — 1Determines certain device modes
Oscillator mode, WDT reset, copy protectionSets device state on power-up
Configured during EEPROM programmingMapped to program memory location 2007h
Not accessible at run time
1 = Pin function = MCLR0 = Pin function = digital I/O
MCLR (master clear) Pin FunctionMCLRE
1 = PWRT disabled0 = PWRT enabled
Power‐up Timer EnablePWRTE
1 = BOR enabled0 = BOR disabled
Brown‐out Reset EnableBODEN
1 = Code protection off0 = Data EEPROM Memory code protected
Data EEPROM Code ProtectionDP
11 = Code protection off10 = device dependent01 = device dependent00 = memory code protected
Code ProtectionCP1:CP0
101Dr. Martin LandPIC MicrocontrollerEmbedded Systems — Hadassah College — Spring 2012
PIC Configuration Bits — 2
111 = EXTRC oscillator, with CLKOUT
110 = EXTRC oscillator
101 = INTRC oscillator, with CLKOUT
100 = INTRC oscillator
011 = Reserved
010 = HS oscillator
001 = XT oscillator
000 = LP oscillator
Oscillator Selection
For devices with internal RCFOSC2:FOSC0
11 = RC oscillator
10 = HS oscillator
01 = XT oscillator
00 = LP oscillator
Oscillator Selection
For devices with no internal RCFOSC1:FOSC0
1 = WDT enabled0 = WDT disabled
Watchdog Timer EnableWDTE