0% found this document useful (0 votes)
33 views194 pages

MC PIC New

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views194 pages

MC PIC New

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 194

PIC uC : General Features

◼ RISC CPUs with Harvard Architecture


◼ 8-bit, 16-bit, 32-bit

◼ Pipelined Architecure
◼ Number of I/O pins: 4-70
◼ Fixed Reset and Interrupt Vector
◼ A/D converters with 8/10-bit resolution
◼ Memory types and sizes:
◼ Flash; OTP; ROM

◼ 0.5k – 256k

1
Why PIC is popular?
◼ low cost ,wide availability with high clock speed
◼ availability of low cost or free development tools
◼ Only 37 instructions to remember
◼ serial programming and re-programming with flash
memory capability
◼ Its code is extremely efficient, allowing the PIC to
run with typically less program memory than its
larger competitors
◼ PIC is very small and easy to implement for non-
complex problems and usually accompanies to the
microprocessors as an interface
2
Architecture
◼ The high performance of the PICmicro® microcontroller can
be attributed to the following architectural features:
◼ Harvard Architecture
◼ Instruction Pipelining
◼ Large Register File
◼ Single Cycle Instructions
◼ Single Word Instructions
◼ Long Word Instructions
◼ Reduced Instruction Set
◼ Orthogonal Instruction Set

3
4
5
Harvard Architecture
Von Neumann ◼ Von Neumann Architecture:
Architecture ◼ Fetches instructions and data
from a single memory space
◼ Limits operating bandwidth

Program
Harvard Architecture:
8-bit Bus
& Data ◼
Memory
CPU ◼ Uses two separate memory
spaces for program
Harvard instructions and data
Architecture
◼ Improved operating
bandwidth
8-bit Bus Data
◼ Allows for different bus widths
Memory

16-bit Bus
CPU

Program
Memory
6
7
8
9
PIC18F – Block Digram

10
PIC18F – Simplified Block Diagram

11
Microprocessor Unit
◼ Arithmetic Logic Unit (ALU)
◼ Instruction decoder
◼ Status register that stores flag
◼ WREG – working register
◼ Registers
◼ Program Counter (PC)
◼ Bank Select Register (BSR)
◼ File Select Registers (FSRs)
◼ Control Unit

S2N Systems
PIC18F - Buses
◼ Address bus
◼ 21-bit address bus for Program Memory

◼ Addressing capacity: 2 MB
◼ 12-bit address bus for Data Memory
◼ Addressing capacity: 4 KB
◼ Data bus
◼ 16-bit instruction/data bus for Program

Memory
◼ 8-bit data bus for Data Memory

◼ Control signals
◼ Read and Write 13
Register File Concept
Register File Concept:
Data Memory
(Register File) All of data memory is
part of the register file,
w f 07h so any location in data
ALU 08h memory may be
09h operated on directly

Data Bus
0Ah
All peripherals are
d
0Bh
mapped into data
w f 0Ch
memory as a series of
0Dh
registers
0Eh

0Fh Orthogonal Instruction


10h Set: ALL instructions
WREG can operate on ANY
data memory location
The Long Word
Decoded Instruction Instruction format
Opcode d a Address
from Program Memory: allows a directly
addressable register file
Arithmetic/Logic Function Address of Second Source
to be Performed Result Operand
Destination

14
PIC18 Instruction Set Overview

Byte Oriented Operations negf f,a Negate f


addwf f,d,a Add WREG and f rlcf f,d,a Rotate Left f through Carry
addwfc f,d,a Add WREG and Carry bit to f rlncf f,d,a Rotate Left f (No Carry)
andwf f,d,a AND WREG with f rrcf f,d,a Rotate Right f through Carry
clrf f,a Clear f rrncf f,d,a Rotate Right f (No Carry)
comf f,d,a Complement f setf f,a Set f
cpfseq f,a Compare f with WREG, skip = subfwb f,d,a Subtract f from WREG with borrow
cpfsgt f,a Compare f with WREG, skip > subwf f,d,a Subtract WREG from f
cpfslt f,a Compare f with WREG, skip < subwfb f,d,a Subtract WREG from f with borrow
decf f,d,a Decrement f swapf f,d,a Swap nibbles in f
decfsz f,d,a Decrement f, Skip if 0 tstfsz f,a Test f, skip if 0
dcfsnz f,d,a Decrement f, Skip if Not 0 xorwf f,d,a Exclusive OR WREG with f
incf f,d,a Increment f
incfsz f,d,a Increment f, Skip if 0
infsnz f,d,a Increment f, Skip if Not 0 Bit Oriented Operations
iorwf f,d,a Inclusive OR WREG with f bcf f,b,a Bit Clear f
movf f,d,a Move f bsf f,b,a Bit Set f
movff fs,fd Move fs (src) to fd (dst) btfsc f,b,a Bit Test f, Skip if Clear
movwf f,a Move WREG to f btfss f,b,a Bit Test f, Skip if Set
mulwf f,a Multiply WREG with f btg f,b,a Bit Toggle f

15
PIC18 Instruction Set Overview
Control Operations Literal Operations
bc n Branch if Carry addlw k Add literal and WREG
bn n Branch if Negative andlw k AND literal with WREG
bnc n Branch if Not Carry iorlw k Inclusive OR literal with WREG
bnn n Branch if Not Negative lfsr f,k Move 12-bit literal to FSR
bnov n Branch if Not Overflow movlb k Move literal to BSR<3:0>
bnz n Branch if Not Zero movlw k Move literal to WREG
bov n Branch if Overflow mullw k Multiply literal with WREG
bra n Branch Always retlw k Return with literal in WREG
bz n Branch if Zero sublw k Subtract WREG from literal
call n,s Call subroutine xorlw k Exclusive OR literal with WREG
clrwdt Clear Watchdog Timer
daw Decimal Adjust WREG
goto n Go to address Data Memory  Program Memory Operations
nop No Operation tblrd* Table Read
pop Pop top of return stack (TOS) tblrd*+ Table Read with post-increment
push Push top of return stack (TOS) tblrd*- Table Read with post-decrement
rcall n Relative Call tblrd+* Table Read with pre-increment
reset Software device RESET tblwt* Table Write
retfie s Return from interrupt tblwt*+ Table Write with post-increment
return s Return from subroutine tblwt*- Table Write with post-decrement
sleep Go into standby mode tblwt+* Table Write with pre-increment

16
Memory Types
◼ Program Flash Memory
◼ Configuration Words
◼ Device ID
◼ User ID
◼ Program Memory
◼ Data Memory (File Registers)
◼ Common Core Registers
◼ Special Function Registers (SFR)
◼ General Purpose Registers (GPR)
◼ Common RAM
◼ Data EEPROM Memory
17
Program Memory Organization
◼ Program memory size can
be 32K word instructions
◼ Divided into multiple 2KW
pages
◼ Allows single word/single
cycle execution
◼ Paging is only a concern
when using CALL or GOTO
instructions, or when
directly modifying the
program counter
18
Program Memory Organization
◼ 21-Bit Program Counter
◼ 2MB Address Space
◼ PC<0> always = 0
◼ 16-bit Program Memory is
Byte Addressable
◼ Reset Vector @ 0x00
◼ Interrupt Vectors
◼ High Priority @ 0x08
◼ Low Priority @ 0x18

19
20
21
22
23
24
Data Memory Organization
◼ Data Memory up to 4k 000h
07Fh
Access RAM PIC16F8F2520/4520
Register File Map
bytes 080h
0FFh
Bank 0 GPR

◼ Divided into 256 byte 100h


Bank 1

banks
GPR
1FFh
200h
◼ Half of bank 0 and half Bank 2
GPR Access Bank

of bank 15 form a 2FFh


Access RAM
00h
7Fh

virtual bank that is D00h


Access SFR
80h
FFh

accessible no matter Bank 13


GPR
256 Bytes

which bank is selected DFFh


E00h

BSR determines which


Bank 14
◼ GPR
EFFh

bank is currently F00h


F7Fh
Bank 15 GPR

selected F80h
FFFh Access SFR
25
26
27
28
PIC18 Oscillator Options
XT Standard frequency crystal oscillator 100kHz - 4MHz
HS High frequency crystal oscillator DC - 40MHz
HS+PLL High frequency crystal with 4x PLL 4MHz - 10MHz
LP Low frequency crystal oscillator 5kHz - 200kHz
RC External RC oscillator DC - 4MHz
RCIO External RC oscillator, OSC2=RA6 DC - 4MHz
INTRC Internal RC oscillator Various
EC External Clock, OSC2=fosc/4 DC - 40MHz
ECIO External Clock, OSC2=RA6 DC - 40MHz

◼ Selectable clock options provide greater flexibility for the


designer:
◼ LP Oscillator designed to draw least amount of current
◼ RC or INTRC provide ultra low cost oscillator solution
◼ XT optimized for most commonly used oscillator frequencies
◼ HS optimized to drive high frequency crystals or resonators
◼ Speed ranges are guidelines only
◼ Instruction speed = 1/4 clock speed (Tcyc = 4 * Tclk) 29
In-Circuit Serial Programming
Pin Function
◼ Only two pins required for
VPP Programming Voltage = 13V
programming VDD Supply Voltage
◼ Convenient for In-System VSS Ground
Programming of RB6 Clock Input
RB7 Data I/O & Command Input
◼ Calibration Data
◼ Serialization Data
◼ Supported by MPLAB® PM3 & ICD2
Application PCB VDD VDD

MCLR/VPP

ICSP ICSP Connector


Connector
PIC18Fxxxx

VDD

VSS

RB6

RB7

Isolation
To application circuit
circuits

30
Development Tools [1]
◼ MPLAB IDE
◼ Older Version (Only works on Windows OS)
◼ Supports Various Microchip Compliers & Simulator
◼ HITECH, PICC, C18, C32 etc.
◼ Also Supports 3rd Party Compilers and Simulators
◼ IAR, CCS
◼ MPLABX IDE
◼ Latest – works on Linux OS as well as Windows
◼ Supports Various Microchip Compliers & Simulator
◼ XC8, XC16, XC32
◼ Also Supports 3rd Party Compilers and Simulators
◼ IAR, CCS
31
Development Tools [2]
◼ MPLAB SIM Simulator
◼ Proteus VSM – 3rd Party Simulator
◼ Programmer and Debugger
◼ PICKIT3
◼ ICD3
◼ REAL ICE
◼ 3rd Party Programmers

32
Microcontroller Design Environment

33
Bootloaders
◼ Piece of code which runs at start-up soon after
reset
◼ A bootloader is a small OS, or application,
designed to download firmware in the
embedded device (MCU's internal or external
memory).
◼ Limited functionality:
◼ Firmware upgrades
◼ Application integrity verification
◼ Run the application
34
Programming with Bootloader

◼ Firmware upgrade - DIY


◼ No additional hardware
◼ Simple PC host application
◼ Avoids expensive recalls
35
Boot loader Concept

36
PIC18 Common Peripherals

◼ Digital I/O Ports


◼ Analog Comparator
◼ Analog to Digital Converter
◼ Timers (0,1,2,3)
◼ Capture, Compare, PWM (CCP)
◼ Addressable USART (AUSART)
◼ Master Synchronous Serial Port (MSSP)

37
Digital I/O Ports [1]
◼ Up to 70 bi-directional I/O pins
◼ Some multiplexed with peripheral functions
◼ High drive capability
◼ 25mA source/sink capability
◼ Can directly drive LEDs
◼ Direct, single cycle bit manipulation
◼ Each pin has individual direction control under S/W
◼ 4kV ESD protection diodes
◼ Based on human body model
◼ Most of pins multiplexed with analog functions
◼ After reset:
◼ Digital I/O default to Input (Hi-Z)
◼ Analog capable pins default to analog 38
PIN DIAGRAM

39
40
41
42
43
44
45
46
47
48
49
SFR Associated with I/O Port
◼ TRISx register (Data Direction register): To select
PORT pin as input or output. All port pins are input
by default. Whenever a bit in the TRISx register is a
0, the corresponding bit in PORTx is an output. If
the bit in TRISx is a 1, the corresponding bit in
PORTx is an input.
◼ PORTx register (reads the levels on the pins of the
device)
◼ LATx register (output latch): The data latch (LAT
register) is useful for read-modify-write operations on
the value that the I/O pins are driving.

50
I/O Port Direction Control

I/O Pin Direction Control


TRISB 1 1 0 1 1 0 0 0

PORTB In In Out In In Out Out Out

◼ Bit n in TRISx controls the data direction of


Bit n in PORTx
◼ 1 = Input, 0 = Output
51
Generic I/O Port Operation

52
Digital I/O Ports Structure
VDD
Data Bus D Q
Write PORTx
Q

RESET
I/O Pin
D Q
Write TRISx
Q

VSS

Read PORTx

Internal Data Bus

Write PORTx
Read LATx Read PORTx
Write LATx

LATx Register
(PORTx Output
Latches)

PORTx I/O Pins 53


54
Analog or Digital I/O?
◼ Some I/O pins multiplexed with analog
inputs (analog by default)
◼ ADCON1 used to determine whether pin
is analog in or digital I/O
Bit 7 Bit 0

- - X X 1 1 1 1
VCFG1 VCFG0 PCFG3 PCFG2 PCFG1 PCFG0

Set lower 4 bits to ‘1’ to make all multiplexed pins digital

55
Data Input and Output
TRIS, PORT and LAT Registers

◼ Steps for working with PIC® I/O ports


1 Initialize Output Write to: LATB = 0;
Latches to Known LAT LATBbits.LATB0 = 0;
State

2 Configure Data Write to: TRISB = 0x23;


Direction of Pins TRIS TRISBbits.TRISB0 = 1;

3 Write to outputs Write to: LATB = 0xF0;


a LATBbits.LATB0 = 0;
LAT

3 Read from inputs Read from: myVar = PORTB;


b myVar = PORTBbits.RB0;
PORT

56
57
PIC Programming in C

Write a C18 program to send values 00 to FF to PORT B

#include <PIC18F4550.h>

Void main(void)
{
Unsigned char z;
TRISB =0;
For( z=0;z<255;z++) // unsigned char is range is 0 to 255
PORTB=z;
While(1);
}

58
PIC Programming in C

Write a C18 program to toggle PORT B


#include <PIC18F4550.h>

Void main(void)
{
Unsigned int z;
TRISB =0;
For( z=0;z<=50000;z++) // unsigned char is range is 0
to 65535
{
PORTB=0x00;
PORTB=0xAA;
}
While(1);
}

59
Write a C18 program to send values 00 to FF to PORT B

#include <PIC18F4550.h>

Void main(void)
{

TRISB =0;

While(1) //we can use for(;;)also


{
PORT B=0X55;
PORT B=0XAA;

60
l
Write a C18 program to toggle PORT B
#include <PIC18F4550.h>
Void delay(unsigned int);
Void main(void)
{
TRISB =0;
While(1)
{
PORTB=0x55;
Delay(250);
PORTB=0xAA;
Delay(250);
}
}
Void delay(unsigned int time)
{
Unsigned int i,j;
for(i=0;i<time,i++)
for(j=0;j<165;j++);
}
61
PIC Programming in C

Write a C18 program to toggle only bit RB4 continuously


#include <PIC18F4550.h>
Void delay(unsigned int);
#define mybit PORTBbits.RB4
Void main(void)
{TRISBbits.TRISB4 =0;
While(1)
{Mybit=1;
delay(250);
Mybit=0;
Delay(250);
}}
Void delay(unsigned int time)
{
Unsigned int i,j;
for(i=0;i<time,i++)
for(j=0;j<165;j++);
}
62
Interfacing Switches ,Buzzer &Relay
to PIC 18F4550

#include <p18f4550.h> //Include Controller specific .h

#include "vector_relocate.h”//Vector Remapping for USB HID


Bootloader

//Declarations
#define lrbit PORTBbits.RB4 //SW1 interfaced to RB4
#define rlbit PORTBbits.RB5 //SW2 interfaced to RB5
#define buzzer PORTCbits.RC2 //Buzzer interfaced to RC2
#define relay PORTCbits.RC1 //Relay interfaced to RC1

63
//Function Prototypes
void msdelay (unsigned int time);//Function for delay

//Function Definitions
void msdelay (unsigned int time)//Function for delay
{
unsigned int i, j;
for (i = 0; i < time; i++)
for (j = 0; j < 710; j++); //Calibrated for a 1 ms
delay in MPLAB
}

64
void main() //Main
Program
{
unsigned char val=0;//Variable to latch the switch condition
INTCON2bits.RBPU=0; //To Activate the internal pull on PORTB
ADCON1 = 0x0F; //To disable the all analog inputs

65
TRISBbits.TRISB4=1; //To configure RB4 as input for sensing SW0
TRISBbits.TRISB5=1; //To configure RB5 as input for sensing SW1

TRISCbits.TRISC1=0; //To configure RC1 (relay) as output


TRISCbits.TRISC2=0;//To configure RC2 (buzzer) as output

TRISD = 0x00; //To configure PORTD (LED) as output

PORTD = 0x00;//Initial Value for LED


buzzer = 0;//Initial Value for Buzzer
relay = 0;//Initial Value for Relay

66
while (1) //While loop for repeated operation
{
if (!(lrbit)) //To check whether SW0 is pressed
val = 1; // Latch the status of switch SW0
if (!(rlbit)) //To check whether SW1 is pressed
val = 2; // Latch the status of switch SW1

67
if (val == 1)
{ buzzer = 1;
relay = 1;
PORTD = PORTD >>1; //Shift left by 1 bit
if (PORTD == 0x00)
PORTD = 0x80; // Make the MSB bit equal to 1
msdelay(250);
}
if (val == 2)
{ buzzer = 0;
relay = 0;
PORTD = PORTD<<1;//Shift right by 1 bit
if (PORTD == 0x00)
PORTD = 0x01;// Make the LSB bit eqaul to 1
msdelay(250);
}
}
}

68
Register Map : PIC18F4550
SFR Description Access Reset Value Address
PORTA : RA6 – RA0
TRISA PORTA Direction Register Read/Write 0x7F 0xF92
PORTA PORTA Read/Write Register Read/Write unknown 0xF80
LATA PORTA Output Latch Register Read/Write unknown 0xF89
PORTB: RB7 - RB0
TRISB PORTB Direction Register Read/Write 0xFF 0xF93
PORTB PORTB Read/Write Register Read/Write unknown 0xF81
LATB PORTB Output Latch Register Read/Write unknown 0xF8A
PORTC: RC7 - RC0
TRISC PORTC Direction Register Read/Write 0xFF 0xF94
PORTC PORTC Read/Write Register Read/Write unknown 0xF82
LATC PORTC Output Latch Register Read/Write unknown 0Xf8B
PORTD: RD7 - RD0
TRISD PORTD Direction Register Read/Write 0xFF 0xF95
PORTD PORTD Read/Write Register Read/Write unknown 0xF83
LATD PORTD Output Latch Register Read/Write unknown 0xF8C
PORTD: RE2 – RE1
TRISE PORTE Direction Register Read/Write 0x07 0xF96
PORTE PORTE Read/Write Register Read/Write unknown 0xF84
LATE PORTE Output Latch Register Read/Write unknown 0xF8D

69
Timer/ Counter Module
◼ Need and use of Timer / Counter
◼ No. of Timers / Counters available in PIC
◼ Special features of Timer / Counter
◼ Need and use of Prescaler and Postscaler
◼ Timer operation with Block diagram
◼ SFRs and PINs involved
◼ Delay Calculation
◼ Timers used for on-chip peripherals
◼ Timer Interrupts and its use

70
Timer0 Features

Timer / Counter Operation using Prescaler 71


◼ The Counter mode is selected by setting the
T0CS bit (= 1). In Counter mode, Timer0
increments either on every rising or falling
edge of pin RA4/T0CKI.
◼ The incrementing edge is determined by the
Timer0 Source Edge Select bit, T0SE
(T0CON<4>); clearing this bit selects the
rising edge.

72
Timer / Counter Operation

Timer / Counter Normal Operation

Timer / Counter Operation using Prescaler 73


Timer0 Operation : 8 bit Mode

Timer 0 in 8-bit Mode

74
75
76
77
78
79
Prescaler to Generate Large
Time Delay

80
Prescaler to Generate Large
Time Delay

81
◼ TMR0H is not the actual high byte of Timer0 in
16-bit mode. It is actually a buffered version
of the real high byte of Timer0 which is not
directly readable nor writable
◼ TMR0H is updated with the contents of the
high byte of Timer0 during a read of TMR0L.
◼ This provides the ability to read all 16 bits of
◼ Timer0 without having to verify that the read
of the high and low byte were valid, due to a
rollover between successive reads of the high
and low byte. 82
◼ A write to the high byte of Timer0 must also
take place through the TMR0H Buffer register.
◼ The high byte is updated with the contents of
TMR0H when a write occurs to TMR0L. This
allows all 16 bits of Timer0 to be updated at
once.

83
Timer0 Operation : 16 bit Mode
FOSC/4 0 TMR0IF
1
T0CKI Clock
1 High Byte TMR0L
Sync
Programmable
0
Prescaler READ
WRITE
TMR0L
T0SE T0CS TMR0L

T0PS2:T0PS0 PSA TMR0H

T0CON Register
TMR0ON T08BIT T0CS T0SE PSA T0PS2:0

Source Edge Select


1 = increment TMR0 on rising edge
0 = increment TMR0 on falling edge

84
Registers associated with Timer0

85
86
87
88
89
Timer Delay Calculations

90
91
92
93
94
95
Interrupt Logic (Legacy Mode)
TMR0I Core Interrupts
F
TMR0IE
Other Core
Interrupts Wakeu
p to
CPU
TMR1I Peripheral
F
TMR1IE Interrupts Interrupt
to CPU
Vector to
Other GIE
0x0008
Peripheral
Interrupts

PEIE

96
Interrupt Logic (Priority Mode)

IP INT0IF INT0IE
IE
IF GIEH
Vector to 0x0008

High Priority
Interrupt to
CPU
Wakeup to CPU

Low Priority
Interrupt to
IP CPU
IE Vector to 0x0018
IF GIEL

97
PIC18 Interrupt Sources
◼ Interrupt Sources
◼ 3 or 4 External Interrupts (INT0-INT3)
◼ Edge Triggered
◼ Rising or Falling selected in INTCON2 register
◼ PORTB Interrupt on Change (RB4-RB7)
◼ Timer Rollover/Overflow Events
◼ Comparator Output Change
◼ A/D Conversion Complete
◼ Communication Channel Events
◼ Other Peripheral Events…

98
Timer0 Interrupt Programming

99
Timer0 Registers

100
INTCON Register

101
102
103
Interrupt Support
◼ Programmer responsibility:
◼ Provide code for interrupt vector
◼ Provide Interrupt Service Routine (ISR)
◼ Compiler saves:
◼ WREG, BSR, STATUS registers (v3.xx and above)
◼ Programmer saves:
◼ Any additional information

104
Interrupts
How to Create an Interrupt Service Routine

Write a prototype for your interrupt handler function

void HighISR(void); ◼ This is the prototype for the


#pragma code HighVector=0x08
function that will be called
void IntHighVector(void) whenever an interrupt
{ occurs
_asm goto HighISR _endasm
} ◼ Give it any name you like
◼ It is an ordinary function
#pragma interrupt HighISR prototype except:
void HighISR(void) ◼ The return type must be
{ void
/* YOUR CODE HERE */
◼ The parameter list must be
}
void

105
Interrupts
How to Create an Interrupt Service Routine

Start a new code section for the interrupt vector

void HighISR(void); ◼ The section must be


#pragma code HighVector=0x08
named, but the name is
void IntHighVector(void) arbitrary
{
◼ Force the section to be
_asm goto HighISR _endasm
} located at the desired
interrupt vector address:
◼ High Priority = 0x08
#pragma interrupt HighISR
void HighISR(void) ◼ Low Priority = 0x18
{
/* YOUR CODE HERE */
}

106
Interrupts
How to Create an Interrupt Service Routine

Populate the interrupt vector

void HighISR(void); ◼ Write a function to be


#pragma code HighVector=0x08
located at the interrupt
void IntHighVector(void) vector
{ ◼ The name is arbitrary, but it
_asm goto HighISR _endasm must not be the same as the
}
section name
◼ The return type and
#pragma interrupt HighISR parameter list must be void
void HighISR(void)
◼ Insert one line of inline
{
/* YOUR CODE HERE */ assembly code to goto
} your interrupt handler
function (HighISR)
107
Interrupts
How to Create an Interrupt Service Routine

Tell compiler which function is an interrupt handler

void HighISR(void); ◼ This tells the compiler to


#pragma code HighVector=0x08
treat this function a bit
void IntHighVector(void) differently from ordinary
{ functions (more soon…)
_asm goto HighISR _endasm
} ◼ For high priority interrupt
handler use:
#pragma interrupt
#pragma interrupt HighISR
void HighISR(void) ◼ For low priority interrupt
{ handler use:
/* YOUR CODE HERE */
}
#pragma interruptlow

108
Interrupts
How to Create an Interrupt Service Routine

Write your interrupt handler function

void HighISR(void); ◼ Just like a normal function


#pragma code HighVector=0x08
except:
void IntHighVector(void) ◼ Return type must be void
{ ◼ Parameters must be void
_asm goto HighISR _endasm
}
◼ May need to do context save
and restore on any global
variables you modify
#pragma interrupt HighISR ◼ If global variable is
void HighISR(void) intentionally changed by
{ interrupt, the variable must
/* YOUR CODE HERE */ be declared as volatile
}
◼ You are still responsible for
clearing interrupt flags
109
Interrupts
Firmware Engineer's Responsibilities

◼ You must enable the interrupt source


◼ You must assign the interrupt priority levels
◼ You must clear the interrupt flag manually
◼ Example: PIRnbits.FlagName = 0;
◼ You must save any registers/variables you access in
the ISR's code if they are not handled automatically
by the compiler
◼ Add a save list to the interrupt attribute
◼ Save them manually in your ISR code
◼ Variables modified by an interrupt should be tagged
with the volatile keyword
110
111
112
113
114
115
Timer1 and Timer3
◼ 16-bit Timer / Counter
◼ Timer, Synchronous Counter or Asynchronous
Counter
◼ Can operate from separate external crystal
◼ Two read/write 8-bit registers
◼ 1, 2, 4, or 8 Prescaler
◼ Interrupt on overflow from FFFFh to 0000h

116
Timer1 and Timer3
Timer 1 Oscillator 0
T1OSO/
1
T13CKI Prescaler Sync 1
1, 2, 4, 8 Detect
FOSC/4 0
T1OSI Sleep Input T1SYNC
T1OSCEN TMR1CS
TMR1ON
T1CKPS1: T1CKPS0

TMR1IF

Clear Timer 1
High Byte TMR1L
(CCP Special Event Trigger)
READ
TMR1L WRITE
TMR1L

TMR1H
RD16 T1RUN T1CKPS1:0 T1OSCEN T1SYNC TMR1CS TMR1ON

Bit 7 Bit 0
T1CON Register
8-bit Data Bus

117
Timer2
◼ 8-bit Timer with prescaler and postscaler
◼ Used as PWM time base
◼ TMR2 is readable & writable
◼ TMR2 resets on match with PR2
◼ Match with PR2 generates interrupt
◼ Used as baud clock for MSSP (SPI)

118
Timer2
T2CON Register
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
- T2OUTPS3 T2OUTPS2 T2OUTPS1 T2OUTPS0 TMR2ON T2CKPS1 T2CKPS0
bit 7 bit 0

00 = 1:1 TMR2 Postscale 0000 = 1:1


01 = 1:4 Value Selection Bits 0001 = 1:2
1x = 1:16 T2OUTPS3:T2OUTPS0
1111 = 1:16
TMR2 Prescale Value
1:1 to 1:16
Selection Bits Postscaler
TMR2IF
T2CKPS1:T2CKPS0
Timer 2 Output
(To PWM or MSSP)
Reset TMR2/PR2 Match
1:1, 1:4, 1:16
FOSC/4 Prescaler
TMR2 Comparator PR2

8-bit Data Bus

119
Timer Comparison
TIMER 0 TIMERS 1 & 3 TIMERS 2 & 4

SIZE OF REGISTER 8-bits or 16-bits 8-bits


16-bits
CLOCK SOURCE Fosc/4 Fosc/4 Fosc/4
(Internal)

CLOCK SOURCE T0CKI pin T13CKI pin or None


(External ) Timer 1 oscillator
(T1OSC)
CLOCK SCALING Prescaler 8-bits Prescaler 2-bits Prescaler
AVAILABLE
(1:2→1:256) (1:1, 1:2, 1:4, (1:1,1:4,1:16)
(Resolution)
1:8) Postscaler
(1:1→1:16)
INTERRUPT EVENT On overflow On overflow TMR REG matches
FFh→00h FFFFh→0000h PR2
CAN WAKE PIC FROM NO YES NO
SLEEP?

120
Hands-on session
◼ Lab 5 : Generate the Delay using Timer0 for
blinking the LED’s at the rate of 10Hz

121
Timer0 Register Map
SFR Description Access Reset Value
T0CON Timer0 Control Register Read/Write 0xFF
TMR0L Timer0 Register Lower Byte Read/Write UNKNOWN
TMR0H Timer0 Register Higher Byte Read/Write 0x00
INTCON Interrupt Control Register Read/Write 0x00

122
T0CON: Timer0 Control Register

Bit No. Control Bit Description


Timer0 On/Off Control bit
Bit 7 TMR0ON
1 = Enables Timer0, 0 = Stops Timer0
Timer0 8-Bit/16-Bit Control bit
Bit 6 T08BIT 1 = Timer0 is configured as an 8-bit timer/counter
0 = Timer0 is configured as a 16-bit timer/counter
Timer0 Clock Source Select bit
Bit 5 T0CS 1= Transition on T0CKI pin
0 = Internal instruction cycle clock (CLKO)
Timer0 Source Edge Select bit
Bit 4 T0SE 1 = Increment on high-to-low transition on T0CKI pin
0 = Increment on low-to-high transition on T0CKI pin
Timer0 Prescaler Assignment bit
Bit 3 PSA 1 = TImer0 prescaler is NOT assigned.
0 = Timer0 prescaler is assigned.
Timer0 Prescaler Select bits
111 = 1:256 Prescale value
110 = 1:128 Prescale value
101 = 1:64 Prescale value
Bit 2-0 T0PS2:T0PS0 100 = 1:32 Prescale value
011 = 1:16 Prescale value
010 = 1:8 Prescale value
001 = 1:4 Prescale value
000 = 1:2 Prescale value
123
INTCON: Interrupt Control Register

Bit No. Control Bit Description


Bit 7 GIE/GIEH Global Interrupt Enable bit
When IPEN = 0:
1 = Enables all unmasked interrupts
0 = Disables all interrupts
When IPEN = 1:
1 = Enables all high priority interrupts
0 = Disables all high priority interrupts

Bit 6 PEIE/GIEL Peripheral Interrupt Enable bit


Bit 5 TMR0IE TMR0 Overflow Interrupt Enable bit
1 = Enables the TMR0 overflow interrupt
0 = Disables the TMR0 overflow interrupt

Bit 2 TMR0IF TMR0 Overflow Interrupt Flag bit


1 = TMR0 register has overflowed (must be cleared in software)
0 = TMR0 register did not overflow

124
Time delay generation using timer0
◼ Load the proper value in T0CON indicating which
timer mode, clock source, prescaler assignment.
◼ Load the registers TMR0H first and then TMR0L with
initial count values. Delay generated is Depends upon
the initial count value.
◼ Start the timer by setting TMR0ON bit in T0CON.
◼ Keep the monitoring the timer flag (TMR0IF).
◼ Get out of the loop when TMR0IF becomes high.
◼ Stop the timer.
◼ Clear the TMR0IF flag for the next round.
◼ Go back to the step 2 to load TMR0H and TMR0L
values.
125
Calculation for generating square wave [1]

◼ Desired frequency of Square Wave Fs = 10 Hz


◼ Ts = 1/Fs = 1/10 = 0.1 second
◼ On Period and OFF period of square wave =
Ts/2 = 0.05s = 50 ms
◼ Maximum delay generated by Timer 0 without
pre scaler is 5.46 ms.
◼ Time Delay (Td) = (65536 - NNNNN) x Time Period TF
◼ Maximum delay = (65536 – 00000) x 0.0833 us
= 5.46 ms

126
Calculation for generating square wave [2]

◼ For Operating Frequency Fosc = 48MHz.


◼ Selecting Prescaler 1:16
◼ Timer Clock source = Fosc/4
◼ Timer Clock Freq. = FT = Fosc/4
= 48x106/4 = 12 MHz
◼ Teq = TF * Prescaler vale = 0.083 us x 16 = 1.333 us
◼ To get n, n= Td/Teq = 50ms/1.333 us = 37502
◼ (yyxx)10 = 65536 – n = 65536 – 37502 = 28034
◼ (28034)10 = (6D82)16 should be loaded in
TMR0H:TMR0L.

127
Enabling Interrupts (Contd..)
◼ Set Peripheral Interrupt Priority
◼ Only needed if using Priority Mode
◼ 1 = High Priority, 0 = Low Priority
IPR1 Register
PSPIP ADIP RCIP TXIP SSPIP CCP1IP TMR2IP TMR1IP

PSPIP: Parallel Slave Interrupt Priority SSPIP: MSSP Interrupt Priority


ADIP: A/D Converter Interrupt Priority CCPIP: CCP1 Interrupt Priority
RCIP: EUSART Rcv Interrupt Priority TMR2IP: Timer2 Interrupt Priority
TXIP: EUSART Tx Interrupt Priority TMR1IP: Timer1 Interrupt Priority
IPR2 Register
OSCIP CMIP --- EEIP BCLIP HLVDIP TMR3IP CCP2IP

OSCIP: Oscillator Fail Interrupt Priority BCLIP: Bus Collision Interrupt Priority
CMIP: Comparator Interrupt Priority HLVDIP: High/Low Voltage Detect Interrupt Priority
---- Unimplemented Bit TMR3IP: Timer3 Interrupt Priority
EEIP: Data EEPROM/Flash Write CCP2IP: CCP2 Interrupt Priority
Operation Interrupt Priority
128
Enabling Interrupts (Contd..)
◼ Ensure Peripheral Interrupt Flags are clear
◼ If set, an interrupt is pending or being processed
◼ 1 = Set, 0 = Clear

PIR1 Register
PSPIF ADIF RCIF TXIF SSPIF CCPIF TMR2IF TMR1IF
PSPIF: Parallel Slave Interrupt Flag SSPIF: MSSP Interrupt Flag
ADIF: A/D Converter Interrupt Flag CCPIF: CCP1 Interrupt Flag
RCIF: EUSART Rcv Interrupt Flag TMR2IF: Timer2 Interrupt Flag
TXIF: EUSART Tx Interrupt Flag TMR1IF: Timer1 Interrupt Flag
PIR2 Register
OSCIF CMIF --- EEIF BCLIF HLVDIF TMR3IF CCP2IF

OSCIF: Oscillator Fail Interrupt Flag BCLIF: Bus Collision Interrupt Flag
CMIF: Comparator Interrupt Flag HLVDIF: High/Low Voltage Detect Interrupt Flag
---- Unimplemented Bit TMR3IF: Timer3 Interrupt Flag
EEIF: Data EEPROM/Flash Write CCP2IF: CCP2 Interrupt Flag
Operation Interrupt Flag
129
Enabling Interrupts (Contd..)
◼ Set Peripheral Interrupt Enables
◼ 1 = Enabled, 0 = Disabled

PIE1 Register
PSPIE ADIE RCIE TXIE SSPIE CCPIE TMR2IE TMR1IE
PSPIE: Parallel Slave Interrupt Enable SSPIE: MSSP Interrupt Enable
ADIE: A/D Converter Interrupt Enable CCPIE: CCP1 Interrupt Enable
RCIE: EUSART Rcv Interrupt Enable TMR2IE: Timer2 Interrupt Enable
TXIE: EUSART Tx Interrupt Enable TMR1IE: Timer1 Interrupt Enable
PIE2 Register
OSCIE CMIE --- EEIE BCLIE HLVDIE TMR3IE CCP2IE

OSCIE: Oscillator Fail Interrupt Enable BCLIE: Bus Collision Interrupt Enable
CMIE: Comparator Interrupt Enable HLVDIE: High/Low Voltage Detect Interrupt Enable
---- Unimplemented Bit TMR3IE: Timer3 Interrupt Enable
EEIE: Data EEPROM/Flash Write CCP2IE: CCP2 Interrupt Enable
Operation Interrupt Enable

130
Enabling Interrupts (Contd..)
◼ Set Leagcy Interrupt Priority
◼ Only needed if using Priority Mode INT0 does not have an
IP bit – it is always a
◼ 1 = High Priority, 0 = Low Priority high priority interrupt

INTCON2 Register
RBPU INTEDG0 INTEDG1 INTEDG2 --- TMR0IP --- RBIP

TMR0IP: TMR0 Overflow Interrupt Priority


RBIP: RB Port Change Interrupt Priority

INTCON3 Register
INT2IP INT1IP --- INT2IE INT1IE --- INT2IF INT1IF

INT2IP: INT2 External Interrupt Priority


INT1IP: INT1 External Interrupt Priority

131
Enabling Interrupts (Contd..)
◼ Ensure legacy Interrupt Flags are Clear
◼ If set, an interrupt is pending or being processed
◼ 1 = Set, 0 = Clear
INTCON Register
GIE/GIEHPEIE/GIELTMR0IE INT0IE RBIE TMR0IF INT0IF RBIF

TMR0IF: TMR0 Overflow Interrupt Flag


INT0IF: INT0 External Interrupt Flag
RBIF: RB Port Change Interrupt Flag

INTCON3 Register
INT2IP INT1IP --- INT2IE INT1IE --- INT2IF INT1IF

INT2IF: INT2 External Interrupt Flag


INT1IF: INT1 External Interrupt Flag

132
Enabling Interrupts (Contd..)
◼ Set legacy Interrupt Enables
◼ 1 = Enabled, 0 = Disabled

INTCON Register
GIE/GIEHPEIE/GIELTMR0IE INT0IE RBIE TMR0IF INT0IF RBIF

TMR0IE: TMR0 Overflow Interrupt Enable


INT0IE: INT0 External Interrupt Enable
RBIE: RB Port Change Interrupt Enable

INTCON3 Register
INT2IP INT1IP --- INT2IE INT1IE --- INT2IF INT1IF

INT2IE: INT2 External Interrupt Enable


INT1IE: INT1 External Interrupt Enable

133
Interrupt Support
◼ Programmer responsibility:
◼ Provide code for interrupt vector
◼ Provide Interrupt Service Routine (ISR)
◼ Compiler saves:
◼ WREG, BSR, STATUS registers (v3.xx and above)
◼ Programmer saves:
◼ Any additional information

134
Interrupts
How to Create an Interrupt Service Routine

Write a prototype for your interrupt handler function

void HighISR(void); ◼ This is the prototype for the


#pragma code HighVector=0x08
function that will be called
void IntHighVector(void) whenever an interrupt
{ occurs
_asm goto HighISR _endasm
} ◼ Give it any name you like
◼ It is an ordinary function
#pragma interrupt HighISR prototype except:
void HighISR(void) ◼ The return type must be
{ void
/* YOUR CODE HERE */
◼ The parameter list must be
}
void

135
Interrupts
How to Create an Interrupt Service Routine

Start a new code section for the interrupt vector

void HighISR(void); ◼ The section must be


#pragma code HighVector=0x08
named, but the name is
void IntHighVector(void) arbitrary
{
◼ Force the section to be
_asm goto HighISR _endasm
} located at the desired
interrupt vector address:
◼ High Priority = 0x08
#pragma interrupt HighISR
void HighISR(void) ◼ Low Priority = 0x18
{
/* YOUR CODE HERE */
}

136
Interrupts
How to Create an Interrupt Service Routine

Populate the interrupt vector

void HighISR(void); ◼ Write a function to be


#pragma code HighVector=0x08
located at the interrupt
void IntHighVector(void) vector
{ ◼ The name is arbitrary, but it
_asm goto HighISR _endasm must not be the same as the
}
section name
◼ The return type and
#pragma interrupt HighISR parameter list must be void
void HighISR(void)
◼ Insert one line of inline
{
/* YOUR CODE HERE */ assembly code to goto
} your interrupt handler
function (HighISR)
137
Interrupts
How to Create an Interrupt Service Routine

Tell compiler which function is an interrupt handler

void HighISR(void); ◼ This tells the compiler to


#pragma code HighVector=0x08
treat this function a bit
void IntHighVector(void) differently from ordinary
{ functions (more soon…)
_asm goto HighISR _endasm
} ◼ For high priority interrupt
handler use:
#pragma interrupt
#pragma interrupt HighISR
void HighISR(void) ◼ For low priority interrupt
{ handler use:
/* YOUR CODE HERE */
}
#pragma interruptlow

138
Interrupts
How to Create an Interrupt Service Routine

Write your interrupt handler function

void HighISR(void); ◼ Just like a normal function


#pragma code HighVector=0x08
except:
void IntHighVector(void) ◼ Return type must be void
{ ◼ Parameters must be void
_asm goto HighISR _endasm
}
◼ May need to do context save
and restore on any global
variables you modify
#pragma interrupt HighISR ◼ If global variable is
void HighISR(void) intentionally changed by
{ interrupt, the variable must
/* YOUR CODE HERE */ be declared as volatile
}
◼ You are still responsible for
clearing interrupt flags
139
Interrupts
Firmware Engineer's Responsibilities

◼ You must enable the interrupt source


◼ You must assign the interrupt priority levels
◼ You must clear the interrupt flag manually
◼ Example: PIRnbits.FlagName = 0;
◼ You must save any registers/variables you access in
the ISR's code if they are not handled automatically
by the compiler
◼ Add a save list to the interrupt attribute
◼ Save them manually in your ISR code
◼ Variables modified by an interrupt should be tagged
with the volatile keyword
140
SFRs

141
142
143
144
145
146
147
PWM : Introduction (1)
◼ PWM stands for Pulse Width Modulation.
◼ PWM is a way to encode data such that it corresponds to the
width of the pulse given a fixed frequency.
◼ It is also a way to control motors,
power circuits, etc. using the
‘width’ of the pulse.
◼ PWM has numerous uses like
Motion Control, Dimming,
Encoding Analog Signal into its
Digital form, in Power Regulation.
◼ PWM changes the average voltage
and current by fast on off
switching. By changing the on
time, the output voltage can be 0
to 100%. 148
PWM : Introduction (2)
◼ PWM Frequency is the rate at which a PWM pulse is repeated.
It can be also called as the “Repetition Rate”.
◼ Frequency is the inverse of the Period. Period (T) is the Time
required for a new pulse to arrive – it is basically the sum of
ON time (T-ON) and OFF time (T-OFF) of a PWM cycle.
◼ The DUTY-CYCLE is percentage of period required for T-ON.

◼ Period i.e T = 10ms


◼ Frequency = 100Hz
◼ T-ON = 3.5ms
◼ T-OFF = 6.5ms
◼ DutyCyle = 35% 149
PWM Mode (e.g. CCP2)

CCPxCON<5:4>

Master CCPR2L 5 4
High Time
(Duty Cycle)
Duty Cycle

Slave CCPR2H TMR2 = CCPRxH:2


LSb

CCPx Output VDD


Comparator R Q
VSS
S
TB1 TB0
Corresponding TMR2 = PR2 TMR2 = PR2
TMR2 * *
TRIS Bit
Period
Bits from
Comparator internal Q clock
Clear Timer, or from Pre-
CCPx pin and scalar
latch D.C.
PR2 Period

150
PWM Output Waveform

151
Configuring CCPx for PWM
◼ Set PWM Period by writing to PR2 register
◼ Set PWM Duty Cycle by writing to CCPRxL and
CCPxCON<5:4> bits
◼ Make the CCPx pin an output by clearing the appropriate
TRIS bit
◼ Set the TMR2 prescale value, then enable TMR2 by
writing to T2CON
◼ Configure the CCPx module for PWM mode

152
PWM Configuration: Step 1
Calculating the Period Value

TPWM = (PR2 + 1)  4  TOSC  TMR2PRE

◼ TPWM = Desired PWM Signal Period = 1 / fPWM

◼ PR2 = TMR2’s Period Register

◼ TOSC = System Oscillator Period = 1 / fOSC

◼ TMR2PRE = TMR2 Prescale Value (1, 4, or 16)

153
PWM Configuration: Step 1
Calculating the Period Value

◼ Rearranging the equation we get:

fOSC
PR2 = -1
4  fPWM  TMR2PRE
Choose TMR2PRE to ensure that PR2 is in the range of 0 to 255
for the desired PWM frequency.

TMR2PRE may be 1, 4, or 16.

154
PR2 value to 4KHz PWM Freq.
◼ For Fosc = 48 MHz, Tosc= 20.83 ns
◼ PWM Freq.= 4KHz, PWM period = 250 us
◼ TMR2 Prescaler Value = 16

155
PWM Configuration: Step 2
Calculating the Duty Cycle Value

DCPWM = (CCPRxL:CCPxCON<5:4>)  TOSC  TMR2PRE

◼ DCPWM = Desired PWM Duty Cycle (time, not %)

◼ CCPR2L = Upper 8-bits of Duty Cycle Value

◼ CCP2CON<5:4> = Low 2-bits of Duty Cycle Value

◼ TOSC = System Oscillator Period

◼ TMR2PRE = TMR2 Prescale Value (1, 4, or 16)

156
PWM Configuration: Step 2
Calculating the Duty Cycle Value

◼ Rearranging the equation we get:

%DCPWM  fOSC
CCPR2L:CCP2CON<5:4> =
100  TMR2PRE  fPWM

Choose TMR2PRE to ensure that CCPR2L:CCP2CON<5:4> is in


the range of 0 to 1023 for the desired PWM duty cycle.

TMR2PRE may be 1, 4, or 16.

157
PWM Configuration: Step 2
Calculating the Duty Cycle Value

◼ 10-bit Duty Cycle value is stored across two


registers:
CCPRxL Register
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
DC2B9 DCxB8 DCxB7 DCxB6 DCxB5 DCxB4 DCxB3 DCxB2
bit 7 bit 0
8 Most Significant Bits

CCPxCON Register
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
- - DCxB1 DCxB0 CCPxM3 CCPxM2 CCPxM1 CCPxM0
bit 7 bit 0
2 Least Significant Bits

158
How to get 20% duty Cycle

%DCPWM  fOSC
CCPR2L:CCP2CON<5:4> =
100  fPWM  TMR2PRE

159
PWM Configuration: Step 4
Set TMR2 Prescale Value and Enable TMR2
T2CON Register
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
- T2OUTPS3 T2OUTPS2 T2OUTPS1 T2OUTPS0 TMR2ON T2CKPS1 T2CKPS0
bit 7 bit 0

bit 2 TMR2ON: Timer2 On bit


1 = Timer2 is On
0 = Timer 2 is Off

bit 1-0 T2CKPS1:T2CKPS0: Timer2 Clock Prescale Select bits


00 = Prescaler is 1 T2CKPS1:T2CKPS0
values determined
01 = Prescaler is 4
when calculating PWM
1x = Prescaler is 16 period and duty cycle

For TMR2 Prescaler Value = 16, Timer 2 ON


T2CON = 0x07
160
PWM Values
◼ Fosc = 48 MHz
◼ PWM = 4 Khz
◼ PR2 = 0xBA
◼ T2CON = 07
CCP1CON<5:4>
Duty Cycle CCPR1L Value
DC1B1:DC1B0
20% 0b00100101 (0x25) 0b10 (0x02)
40% 0b00011011 (0x4B) 0b00 (0x00)
60% 0b01110000 (0x70) 0b10 (0x02)
80% 0b10010110 (0x96) 0b00 (0x00)
100% 0b10111011 (0xBB) 0B10 (0x02

161
PWM Configuration: Step 3
Configure the CCP2 Pin as an Output

1 40

Select CCP2 pin


2 39

3 38
◼ Clear corresponding TRIS 4 37
5 RB3/AN9/CCP2(1)
bit 6
36
35 (1)Optional CCP2 on RB3:

PIC18F4520
7 34
8 33 If CONFIG3H<CCP2MX> = 0
9 32 #pragma config CCP2MUX = OFF
10 31
11 30 TRISB<3> = 0
12 29
13 28
14 27
15 26
RC1/T1OSI/CCP2(1) 16 25
17 24
Default CCP2 on RC1:
(1)
18 23
If CONFIG3H<CCP2MX> = 1 19 22
#pragma config CCP2MUX = ON 20 21

TRISC<2> = 0

162
PWM Configuration: Step 5
Configure CCP for PWM Mode
CCP2CON Register
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0
- - DC2B1 DC2B0 CCP2M3 CCP2M2 CCP2M1 CCP2M0
bit 7 bit 0

bit 5-4 DC2B1:DC2B0: PWM Duty Cycle bit 1 and bit 0 for CCP2
These bits are the two LSbs of the 10-bit PWM duty cycle. The 8 MSbs
(DCx9:DCx2) of the duty cycle are found in CCPR2L.
DC2B1:DC2B0 values determined when calculating PWM duty cycle
bit 3-0 CCP2M3:CCP2M0: CCP Module 2 Mode Select bits
0000 = Capture/Compare/PWM disabled (resets CCP module)
0001 = Reserved
0010 = Compare mode, toggle output on match (CCP2IF bit is set)
0011 = Reserved
0100 = Capture mode, every falling edge

11xx = PWM mode

163
#include<P18F4550.H>
#include"vector_relocate.h"
void delay (int c);

void main()
{
TRISCbits.TRISC2=0;
TRISDbits.TRISD5=0;
TRISDbits.TRISD6=0;
PR2=0xBB;
CCP1CON=0x0C;
T2CON=0x07;
PORTDbits.RD5=0;
PORTDbits.RD6=1;
164
while(1)
{
/*CCP1CONbits.DC1B1=1;//100%duty cycle
CCP1CONbits.DC1B0=0;
CCPR1L=0xBB;
delay(2000);*/
CCP1CONbits.DC1B1=0;
CCP1CONbits.DC1B0=0;//80%
CCPR1L=0x96;
delay(2000);
CCP1CONbits.DC1B1=0;
CCP1CONbits.DC1B0=0;//60%
CCPR1L=0x70;

165
delay(2000);
CCP1CONbits.DC1B1=0;
CCP1CONbits.DC1B0=0;
CCPR1L=0x4B;//40 % duty
delay(2000);
CCP1CONbits.DC1B1=1;
CCP1CONbits.DC1B0=0;
CCPR1L=0x25;//20%
delay(2000);
}
}

166
void delay (int c)
{

int i, j;

for(i=0;i<c;i++)
{
for (j=0;j<500;j++)
{
}
}
}

167
10-bit ADC Module in PIC18F

168
ADC Pin Description
Signal Pin No. Symbol
Channel 0 (AN0) 2 RA0/AN0
Channel 1 (AN1) 3 RA1/AN1
Channel 2 (AN2) 4 RA2/AN2/Vref-/CVref
Channel 3 (AN3) 5 RA3/AN3/Vref+
Channel 4 (AN4) 7 RA5/AN4/SS/HLVDIN/C2OUT
Channel 5 (AN5) 8 RE0/AN5/CK1SPP
Channel 6 (AN6) 9 RE1/AN6/CK2SPP
Channel 7 (AN7) 10 RE2/AN7/OESPP
Channel 8 (AN8) 35 RB2/AN8/INT2/VMO
Channel 9 (AN9) 36 RB3/AN9/VPO
Channel 10 (AN10) 34 RB1/AN10/INT1/SCK/SCL
Channel 11 (AN11) 37 RB4/AN11/KBIO/CSSPP
Channel 12 (AN12) 33 RB0/AN12/INT0/FLT0/SDI/SDA

169
ADC Register Map
SFR Description Access Reset Value
ADCON0 A/D Control Register 0 Read/Write 0x00
ADCON1 A/D Control Register 1 Read/Write 0x00
ADCON2 A/D Control Register 2 Read/Write 0x00
ADRESH A/D Result High Register Read unknown
ADRESL A/D Result Low Register Read unknown

170
ADC Control Register 0

171
ADC Control Register 1

172
ADC Control Register 2

173
Choosing ADC Clock Source

174
A/D Acquisition Time Select bits
Acquisition Time Conversion Time
time
VC
VIN
ADRES

10
Acquisition Time is
time
determined by Pin
SOURCE
Capacitance and Source
impedance RS < 10k
ADC

+ Acquisition Time allows V


CHOLD VC Hold Capacitor to
- fully charge to VIN
VSS

175
A/D Acquisition Time Select bits

176
A/D Result Format Select bit

177
ADC Conversion Steps

178
Capture mode

179
180
181
Compare Mode PIC
◼ In compare mode, the 16-bit CCPR1 register value is
constantly compared against either the TMR1 or the TMR3
register pair value shown in the figure given below.
◼ When a match occurs between the CCPR1 Register value and
Timer value, the CCP1IF interrupt flag is generated and one
of the following actions may occur on the associated RC2 pin:
1. Toggle output on the RC2 pin.
2. RC2 pin drives to a High level.
3. RC2 pin drives to a low level.
4. Generate software interrupt
5. Generate a special trigger event.
◼ Now, what output logic will generate when a compare match
occurs depend on the CCP1CON register.
182
◼ Interrupt on Match
◼ Also, remember that after every compare
match between CCPR1 and Timer1/Timer3
CCP1IF interrupt flag is set.
◼ This flag is located at PIR1<bit2> Register.
◼ Also, note that the T3CON register is used to
select Timer1 or Timer3 for compare mode.

183
Steps for Programming
1. Set the CCP1 pin as an output.
2. Configure T3CON Register for Timer1 or Timer 3
1. If Timer1 is used then configure T1CON Register

also.
3. Configure CCP1CON Register for compare mode.
4. Load desired count in CCPR1 (CCPR1H: CCPR1L)
Register.
5. Also, initialize TMR1 or TMR3 register value.
6. Start Timer
7. Wait for CCP1IF (PIR1<2>) interrupt flag to set.
8. Then Clear Timer Register (TMR1 or TMR3).
9. Jump to step 3. 184
Generate a square wave of 1 kHz having a
50% duty cycle
◼ Assume Oscillator frequency = 8MHz
◼ Period of waveform = 1ms (1 KHz given),So
Instruction Cycle = 1/ (FOSC/4) = 1/ (8MHz/4) = 0.5
us
◼ That means Timer will increment its count
continuously after each 0.5us delay.
◼ Timer3 register is used.
◼ Now calculate CCPR1 count.
◼ For 50% Duty Cycle – ON time=OFF time=0.5ms
◼ 0.5ms/0.5us = 1000 i.e. 0x03E8
◼ CCPR1 = 0x03E8
185
void main()
{ OSCCON=0x72; /* Configure internal clock at
8MHz */
TRISCbits.TRISC2=0; /* Configure RC2 pin as
output */
CCP1CON=0x02; /* Module is configured for
compare mode and is set up so that upon a
compare match of CCPR1 and TMR3, RC2 is
driven low*/

186
PIR1bits.CCP1IF=0; /* Clear interrupt flag*/
TMR3=0; /* Clear Timer3 Register*/
T3CON=0xC0; /* Timer3 used for compare mode
with TMR3 register in 16-bit format*/
CCPR1=1000; /* Load a count for generating
1khz*/
T3CONbits.TMR3ON=1; /* Turn On Timer3*/
;}

187
while (1)
{ /* Wait for CCP Interrupt flag to set, it is set on
compare match between CCPR1 and TMR3*/
while(PIR1bits.CCP1IF==0);
PIR1bits.CCP1IF=0;/* Clear interrupt flag */
TMR3=0
}

188
189
Generate another 1KHz waveform
with a 40% duty cycle.
0.4ms/0.5us = 800 i.e. 0x0320
0.6ms/0.5us = 1200 i.e. 0x04B0
Load these values into CCPR1 Register
void main()
{ OSCCON=0x72; /* Configure internal clock at
8MHz */
TRISCbits.TRISC2=0; /* Configure RC2 pin as
output. */
CCP1CON=9; /* Module is configured for compare mode and is set up
so that upon a compare match of CCPR1 and TMR3, RC2 is driven high*/
190
PIR1bits.CCP1IF=0;
TMR3=0;
T3CON=0xC0; /* Timer3 used for capture mode
with TMR3 register in 16-bit format*/
CCPR1=0x320; /* Load a count for generating
0.4ms*/
T3CONbits.TMR3ON=1; /* Turn On Timer3*/

191
while(1) {
/* Wait for CCP Interrupt flag to set, it is set on compare
match between CCPR1 and TMR3*/
while(PIR1bits.CCP1IF==0);
PIR1bits.CCP1IF=0; /* Clear interrupt flag*/ TMR3=0; /*
Clear Timer3 Register*/
CCP1CON=8; /* CCP1 module is configured for compare
mode and is set up so that upon a compare match of
CCPR1 and TMR3, RC2 is driven low*/
CCPR1=0x04B0; /* Load count for generating 0.6ms */

192
while(PIR1bits.CCP1IF==0);
PIR1bits.CCP1IF=0;
TMR3=0; /* Clear Timer3 Register*/
CCP1CON=9;
CCPR1=0x0320; /* Load count for generating
0.4ms */ } }

193
Thank You !!!!

194

You might also like