You are on page 1of 91

EE6008 – MICROCONTROLLER BASED SYSTEM DESIGN

UNIT I INTRODUCTION TO PIC MICROCONTROLLER

Introduction to PIC Microcontroller–PIC 16C6x and PIC16C7x Architecture–PIC16cxx–-


Pipelining - Program Memory considerations – Register File Structure - Instruction Set -
Addressing modes – Simple Operations.
Text Book: Design with PIC Microcontrollers John B. Peatman.
Reference: PIC 16c6x/7x Datasheet
Chapter 1 (pg 16-21)
Chapter 2 (pg 27-43)
Chapter 3 (pg 47-52)

UNIT II INTERRUPTS AND TIMER

PIC micro controller Interrupts- External Interrupts-Interrupt Programming–Loop time


subroutine - Timers-Timer Programming– Front panel I/O-Soft Keys– State machines and key
switches– Display of Constant and Variable strings.
Text Book: Design with PIC Microcontrollers John B. Peatman.
Reference: PIC 16c6x/7x Datasheet
Chapter 4 (pg 71 -84)
Chapter 5 (pg 88-103)
Chapter 6 (pg 109- 133)
Chapter7 (pg 139-141, 148-152)
Chapter 8 (pg157-171)

1
UNIT I INTRODUCTION TO PIC MICROCONTROLLER

SYLLABUS TOPICS:

a. Introduction to PIC Microcontroller


b. PIC 16C6x and PIC16C7x Architecture
c. PIC16cxx–Pipelining
d. Program Memory considerations
e. Register File Structure
f. Instruction Set
g. Addressing modes
h. Simple Operations

ANNA UNIVERSITY QUESTIONS (UQ)

Nov/Dec 2016

1. Draw and explain the architecture of PIC 16 Microcontroller


2. Explain about the various instruction set of PIC Microcontroller
3. Explain about the various Memory organization of PIC Microcontroller.

OTHER POSSIBLE QUESTIONS (Q)

a. Introduction to PIC Microcontroller

1. List the features of 16C6x/7x family.


2. Briefly explain the characteristics and evolution of PIC microcontrollers.

b. PIC 16C6x and PIC16C7x Architect

3. With the help of block diagram explain the architecture of PIC 16C6X/7X microcontroller.

c. PIC16cxx–Pipelining

4. How is the instruction pipelining implemented in PIC microcontrollers?

d. Program Memory considerations

5. Give the program memory organization in PIC microcontroller.

2
e. Register File Structure

6. Discuss in detail about the function of various port pin of PIC micro controller

7. What are the different CPU registers of PIC microcontroller, explain them.

8. Explain the arithmetic-logic unit, working register and status register for a PIC
microcontrollers.

f. Instruction Set

9. Explain the instruction set of PIC microcontroller 16c6x.

g. Addressing modes

10. Explain the addressing modes of PIC 16C6X/7X microcontroller


11. Explain direct and indirect addressing in PIC microcontroller.

h. Simple Operations

12. Explain commonly reoccurring sequences of instructions.


13. Explain the either-or sequence, Decrement of 16 bit counter and testing a 16 bit variable for
zero.
14. Explain the working of LED driver with a suitable program.

3
QUESTIONS AND ANSWERS

QUESTION

Q1. List the features of 16C6x/7x family.


Q2.Briefly explain the characteristics and evolution of PIC microcontrollers.

ANSWER

INTRODUCTION TO PIC MICROCONTROLLER

PIC Microcontrollers

PIC stands for Peripheral Interface Controller coined by Microchip Technology to identify its single
chip microcontrollers. These devices have been phenomenally successful in 8-bit microcontroller
market.
The main reason is that Microchip Technology has constantly upgraded the device architecture and
added needed peripherals to the microcontroller to ’suit customers’ requirements. The
development tools such as assembler and simulator are freely available on the internet.
Low-end Architectures
Microchip PIC microcontrollers are available in various types.
When PIC became available from General Instruments in early 1980’s, the microcontroller
consisted of a very simple processor executing 12-bit wide instructions with basic I/O functions.
These devices are known as low-end architectures. Some of the low-end device past numbers are
12C5XX, 16C5X, and 16C505
Mid-range Architectures
Mid-range Architectures are built by upgrading low-end architecture with more number of
peripherals, more numbers of register and more data memory. Some of the mid-range devices are
16C6X 16C7X, 16F873 Program memory type
C = EPROM
F = Flash
RC = Mask ROM
Popularity of PIC microcontrollers is due to the following factors:
1. Speed: Harvard Architecture, RISC Architecture
1 instruction Cycle = 4 clock cycles.
For 20 MHz clock, most of the instructions are executed in 0.2μs or five instructions per
microsecond.
2. Instruction Set Simplicity:
The instruction set consists of just 35 instructions (as opposed to 111 instructions for 8051)
3. Power on reset
Power-out reset
Watch-dog timer
Oscillator Options

4
• low-power Crystal
• Mid-range Crystal
• High-range Crystal
• RC Oscillator
4. Programmable timer options on chip ADC
5. Up to 12 independent interrupt sources
6. Powerful output pin control 25mA (max.) current sourcing capability.
7. EPROM/OTP/ROM/Flash memory options.
8. Free assembler and simulator support from microchip.

Evolution of PIC Microcontroller

Philosophy of PIC Architecture


 Embedded processing is pervasive
 Electronic intelligence in is everyday products
 Company Philosophy
 Have products that fit the problem
 Many systems can be automated using 8-bit microcontrollers
 Much of product line is 8-bit
Reasons for pervasiveness
 Competitive pressure
 Expanded functionality of products
 Provide differentiation in product from that of competitor
 Cost competitive integrated solution
 Allow creation of new classes of products
Microcontroller Solution
 Microcontroller features
 CPU – processing unit
 Non-volatile program memory

5
 Re-settable non-volatile data memory (EEPROM)
 RAM for data storage
 Direct support for various input/output
Some typical applications
 Automotive air bag systems
 Remote control
 Handheld tools
 Appliances – coffee pot, mixer, stove, refrigerator, dish washer, washer, dryer
 Major home systems – heating and cooling
 Cordless phones and cell phones
 Security systems
 TV, DVD player/recorder, DVR, PVR
 Sound system
4-bit through 32-bit
 4-bit ,Very inexpensive
 8-bit ,Still very cheap – often ~$1.00 per chip
 16 and 32 bit, Priced at $6.00 to 12.00 each
Evaluation of requirements, chip capability, and cost come into design decision
Typical automotive use
 Engine control – 32-bit microcontroller, Fuel flow, fuel mixture, valve timing,
throttle body opening, spark timing
 Transmission control –16-bit microcontroller
 Audio system – 16-bit
 Antilock braking – 16-bit
 Up to fifty 8-bit microcontrollers for functions of , Wiper control, Electric Mirrors,
Air Bags

Features

6
Q3. With the help of block diagram explain the architecture of PIC 16C6X/7X
microcontroller. UQ1. Draw and explain the architecture of PIC 16 Microcontroller (Nov/ Dec-
2016).

ANSWER:
CPU Architecture: The CPU uses Harvard architecture with separate Program and Variable (data)
memory interface. This facilitates instruction fetch and the operation on data/accessing of variables
simultaneously.

HARVARD ARCHITECTURE

7
Architecture (PIC 16c66/67)

8
Architecture (PIC 16c74/74A/77)

9
PIC Microcontroller Clock
Most of the PIC microcontrollers can operate upto 20MHz. One instructions cycle (machine cycle)
consists of four clock cycles.
Instructions that do not require modification of program counter content get executed in one
instruction cycle.
Although the architectures of various midrange 8 - bit PIC microcontroller are not the same, the
variation is mostly interns of addition of memory and peripherals. We will discuss here the
architecture of a standard mid-range PIC microcontroller, 16C74A. Unless mentioned otherwise,
the information given here is for a PIC 16C74A microcontroller Chip.

Architecture of PIC16C74A
The basic architecture of PIC16C74A is shown in fig 17.2. The architecture consists of Program
memory, file registers and RAM, ALU and CPU registers. It should be noted that the program
Counter is 13 - bit and the program memory is organised as 14 - bit word. Hence the program
Memory capacity is 8k x 14 bit. Each instruction of PIC 16C74A is 14 - bit long. The various CPU
registers are discussed here.

CPU registers (registers commonly used by the CPU)


W, the working register, is used by many instructions as the source of an operand. This is similar to
accumulator in 8051. It may also serve as the destination for the result of the instruction execution.
It is an 8 - bit register.
STATUS Register
The STATUS register is a 8-bit register that stores the status of the processor. This also stores carry,
zero and digit carry bits.
STATUS - address 03H, 83H
C = Carry bit DC = Digit carry (same as auxiliary carry) Z = Zero bit NOT_TO and NOT_PD - Used in
conjunction with PIC's sleep mode RP0- Register bank select bit used in conjunction with direct
addressing mode.
FSR Register (File Selection Register, address = 04H, 84H) FSR is an 8-bit register used as data
memory address pointer. This is used in indirect addressing mode.
INDF Register (INDirect through FSR, address = 00H, 80H) INDF is not a physical register.
Accessing INDF access is the location pointed to by FSR in indirect addressing mode.
PCL Register (Program Counter Low Byte, address = 02H, 82H) PCL is actually the lower 8-bits of
the 13-bit program counter. This is a both readable and writable register.
PCLATH Register (Program Counter Latch, address = 0AH, 8AH) PCLATH is a 8-bit register which
can be used to decide the upper 5bits of the program counter. PCLATH is not the upper 5bits of the
program counter. PCLATH can be read from or written to without affecting the program counter.
The upper 3bits of PCLATH remain zero and they serve no purpose. When PCL is written to, the
lower 5bits of PCLATH are automatically loaded to the upper 5bits of the program counter, as
shown in the figure.
Program Counter Stack
An independent 8-level stack is used for the program counter. As the program counter is 13bit, the
stack is organized as 8x13bit registers. When an interrupt occurs, the program counter is pushed

10
onto the stack. When the interrupt is being serviced, other interrupts remain disabled. Hence, other
7 registers of the stack can be used for subroutine calls within an interrupt service routine or
within the mainline program.

The PIC architecture is characterized by the following features:


 Separate code and data spaces (Harvard architecture) for devices other than PIC32, which
has a Von Neumann architecture.
 A small number of fixed length instructions
 Most instructions are single cycle execution (2 clock cycles), with one delay cycle on
branches and skips
 One accumulator (W0), the use of which (as source operand) is implied (i.e. is not encoded
in the opcode)
 All RAM locations function as registers as both source and/or destination of math and other
functions.[2]
 A hardware stack for storing return addresses
 A fairly small amount of addressable data space (typically 256 bytes), extended through
banking
 Data space mapped CPU, port, and peripheral registers
 The program counter is also mapped into the data space and writable (this is used to
implement indirect jumps).

Limits
The PIC architectures have several limits:
 Only one accumulator
 A small instruction set
 Operations and registers are not orthogonal; some instructions can address RAM and/or
immediate constants, while others can only use the accumulator
 Memory must be directly referenced in arithmetic and logic operations, although indirect
addressing is available via 2 additional registers
 Register-bank switching is required to access the entire RAM of many devices

The following limitations have been addressed in the PIC18, but still apply to earlier cores:
 Conditional skip instructions are used instead of conditional jump instructions used by
most other architectures
 Indexed addressing mode is very rudimentary
 Stack:
The hardware call stack is so small that program structure must often be flattened
The hardware call stack is not addressable, so pre-emptive task switching cannot be
implemented
 Software-implemented stacks are not efficient, so it is difficult to generate reentrant code
and support local variables
 Program memory is not directly addressable, and thus space-inefficient and/or time-
consuming to access. (This is true of most Harvard architecture microcontrollers.)

11
Q4. How is the instruction pipelining implemented in PIC microcontrollers?

Pipelining is a technique used to overlap two or more instructions as they are being executed.
• This introduces some parallelism in the execution of instructions, thus reducing the required
execution time.
• The programmer does not need to worry about pipelining, as it is incorporated into the design of
the microcontroller.
• Pipelining is similar to a production line in a factory.
– There, the product is moved between stations, each one of them doing a specific task.
– In a production line with n steps, there are always n products in the process of being
manufactured.
– Let’s assume Ts is the time that the product spends in each station. The total production time will
then be n × Ts.
– But as there is a product coming out from the production line at any Ts, time units, the average
time for product manufacturing is then Ts.
– In an n-stage pipeline, each instruction spends a time equal to TMC for any stage, with TMC being
the time length of a machine cycle.
– Therefore, the time needed to move through all the stages is n × TMC.
– However, because instructions exit the pipeline every TMC seconds, it is possible to assume that
the average time to execute any instruction is TMC .
– Because some instructions, such as control transfer instructions, require additional machine
cycles, the average instruction execution time for these instructions is slightly longer than TMC.

12
Q5. Give the program memory organization in PIC microcontroller.

UQ3.Explain about the various Memory organization of PIC Microcontroller

ANSWER:

13
Data Memory is also known as Register File. Register File consists of two components.
1. General purpose register file (same as RAM).
2. Special purpose register file (similar to SFR in 8051).

The special purpose register file consists of input/output ports and control registers. Addressing
from 00H to FFH requires 8 bits of address. However, the instructions that use direct addressing
modes in PIC to address these register files use 7 bits of instruction only. Therefore the register
bank select (RP0) bit in the STATUS register is used to select one of the register banks.
In indirect addressing FSR register is used as a pointer to anywhere from 00H to FFH in the data
memory.

Data Memory Map

14
Q6. Discuss in detail about the function of various port pin of PIC micro controller

15
PIC 16C74A has 5 I/O Ports. Each port is a bidirectional I/O port. In addition, they have the
following alternate functions.
In addition to I/O pins, there is a Master clear pin (MCLR) which is equivalent to reset in 8051.
However, unlike 8051, MCLR should be pulled low to reset the micro controller. Since
PIC16C74Ahas inherent power-on reset, no special connection is required with MCLR pin to reset
the micro controller on power-on.
There are two VDD pins and two VSS pins. There are two pins (OSC1 and OSC2) for connecting the
crystal oscillator/ RC oscillator. Hence the total number of pins with a 16C74A is 33+7=40. This IC
is commonly available in a dual-in-pin (DIP) package.

Port D alternative function is parallel slave port which enables one PIC microcontroller to be
connected to the data bus of another microprocessor.

16
Q7.What are the CPU registers of PIC microcontroller, explain them.

CPU registers (registers commonly used by the CPU)

W, the working register


W, the working register, is used by many instructions as the source of an operand. This is similar to
accumulator in 8051. It may also serve as the destination for the result of the instruction execution.
It is an 8 - bit register.

STATUS Register
The STATUS register is a 8-bit register that stores the status of the processor.

17
FSR Register (File Selection Register, address = 04H, 84H) FSR is an 8-bit register used as data
memory address pointer. This is used in indirect addressing mode.

INDF Register (INDirect through FSR, address = 00H, 80H) INDF is not a physical register.
Accessing INDF access is the location pointed to by FSR in indirect addressing mode.

PCL Register (Program Counter Low Byte, address = 02H, 82H) PCL is actually the lower 8-bits of
the 13-bit program counter. This is a both readable and writable register.

PCLATH Register (Program Counter Latch, address = 0AH, 8AH) PCLATH is a 8-bit register which
can be used to decide the upper 5bits of the program counter. PCLATH is not the upper 5bits of the
program counter. PCLATH can be read from or written to without affecting the program counter.
The upper 3bits of PCLATH remain zero and they serve no purpose. When PCL is written to, the

18
lower 5bits of PCLATH are automatically loaded to the upper 5bits of the program counter, as
shown in the figure.

For subroutine

Program Counter Stack


An independent 8-level stack is used for the program counter. As the program counter is 13bit, the
stack is organized as 8x13bit registers. When an interrupt occurs, the program counter is pushed
onto the stack. When the interrupt is being serviced, other interrupts remain disabled. Hence, other
7 registers of the stack can be used for subroutine calls within an interrupt service routine or
within the mainline program.

Register File Map


It can be noted that some of the special purpose registers are available both in Bank-0 and Bank-1.
These registers have the same value in both banks. Changing the register content in one bank
automatically changes its content in the other bank.

19
Q8. Explain the arithmetic-logic unit, working register and status register for a PIC
microcontrollers.

Q9. Explain the instruction set of PIC microcontroller 16c6x.


UQ2.Explain about the various instruction set of PIC Microcontroller
ANSWER:

• Data Movement – movf,movlw,movwf


Arithmetic – addlw,addwf,sublw,subwf,incf,decf
• Logical – andlw,andwf,iorlw,iorwf,xorlw,xorwf,rrf,rlf,clrf,clrw,swapf,comf
• Bit Operators – bsf,bcf
• Branching – goto,btfss,btfsc,decfsz,incfsz • Subroutine – call,return,retlw,retfie
• Misc. – sleep,clrwdt,nop

20
If d=0, solution stored in W register, if d=1, solution stored in f (register)

21
Q10. Explain the addressing modes of PIC 16C6X/7X microcontroller
Q11. Explain direct and indirect addressing in PIC microcontroller.

ANSWER

Register Addressing Modes


• There are 3 types of addressing modes in PIC
1. Immediate Addressing Movlw H’0F’
2. Direct Addressing
3. Indirect Addressing

Direct Addressing
• Uses 7 bits of 14 bit instruction to identify a register file address • 8th and 9th bit comes from RP0
and RP1 bits of STATUS register.

Indirect Addressing
• Full 8 bit register address is written the special function register FSR • INDF is used to get the
content of the address pointed by FSR • Exp : A sample program to clear RAM locations H’20’ –
H’2F’ .
For instance, – one general purpose register (GPR) at address 0Fh contains a value of 20 – By
writing a value of 0Fh in FSR register we will get a register indicator at address 0Fh, – and by
reading from INDF register, we will get a value of 20, which means that we have read from the first

22
register its value without accessing it directly (but via FSR and INDF). • It appears that this type of
addressing does not have any advantages over direct addressing, but certain needs do exist during
programming which can be solved smoothly only through indirect addressing. • Indirect addressing
is very convenient for manipulating data arrays located in GPR registers. – In this case, it is
necessary to initialize FSR register with a starting address of the array, and the rest of the data can
be accessed by incrementing the FSR register.

23
Q12. Explain commonly reoccurring sequences of instructions.
Q13. Explain the either-or sequence, Decrement of 16 bit counter and testing a 16 bit
variable for zero.
ANSWER

24
Addition of 8-bit numbers
Case 1: Solution in W register
movlw 0x 05 ; W 05
addlw 0x 02 ;W W + 02; W 05+ 02; W 07.
nop

Case 2: Solution in specified register – here PCL


movlw 0x 03 ; W 03
movwf PCL ; PCL W; PCL 03.
addwf PCL, 1 ;W+PCL; PCL 03+03; PCL 06

Q14. Explain the working of LED driver with a suitable program.

Circuit:

25
Program:

26
27
TWO MARK QUESTIONS AND ANSWERS

UNIT- I

1. State the significant features of PIC microcontrollers.


Ans: Speed: Harvard Architecture, RISC Architecture, Instruction Set Simplicity, Power on reset
Power-out reset, Watch-dog timer, Oscillator Options, Programmable timer options on chip ADC,Up
to 12 independent interrupt sources, EPROM/OTP/ROM/Flash memory options, Free assembler
and simulator support from microchip.

2. Illustrate the pipelining of instructions in PIC

3. Give the register file structure in PIC.

28
4. What are the CPU Registers in PIC microcontroller?

The CPU Registers in PIC microcontroller are W Register, STATUS,FSR, INDF, PCL, PCLATH

5. What is the bit configuration of STATUS Register?

6. Give a brief overview of memory organizations in PIC microcontroller.

The PIC 16C7X family has a 13-bit program counter capable of addressing 8k×14 program memory.
PIC16C74A has 4k×14 program memory. For those devices with less than 8k program memory,
accessing a location above the physically implemented address will cause a wraparound.

29
7. Draw the structure of port pin in PIC microcontroller.

8.What are the addressing modes available in PIC microcontroller?

Immediate, Direct and Indirect addressing modes.

9.List the type of instruction available in PIC microcontroller

• Data Movement
Arithmetic
• Logical
• Bit Operators
• Branching
• Subroutine
• Miscellaneous

10.What are the PORT functions in PIC 16c6x/7x series.

30
11. What is the purpose of W- Work register?
Work register acts as the accumulator in PIC microcontroller.

12. What are the Program memory types in 16C6X 16C7X, 16F873?
C = EPROM
F = Flash
RC = Mask ROM

13. What are the Oscillator Options in PIC microcontroller

• low-power Crystal
• Mid-range Crystal
• High-range Crystal
• RC Oscillator

14. What are the major popularity factors of PIC microcontroller?

Popularity of PIC microcontrollers is due to the following factors:


1. Speed: Harvard Architecture, RISC Architecture, 1 instruction Cycle = 4 clock cycles.
For 20 MHz clock, most of the instructions are executed in 0.2μs or five instructions per
microsecond.
2. Instruction Set Simplicity:
The instruction set consists of just 35 instructions (as opposed to 111 instructions for 8051)

31
15. What are the Data transfer instructions in PIC microcontroller?

Data Movement – movf, movlw, movwf

16. What are the arithmetic instructions in PIC microcontroller?

Arithmetic – addlw,addwf,sublw,subwf,incf,decf

17. What are the Logical instructions in PIC microcontroller?


Logical – andlw,andwf,iorlw,iorwf,xorlw,xorwf,rrf,rlf,clrf,clrw,swapf,comf

18. What are the bit operator instructions in PIC microcontroller?

Bit Operators – bsf,bcf

19. What are the branching instructions in PIC microcontroller?

Branching – goto,btfss,btfsc,decfsz,incfsz

20. What are the subroutine instructions in PIC microcontroller?

Subroutine – call,return,retlw,retfie

21. What are the miscellaneous instructions in PIC microcontroller?

Miscelllaneous – sleep,clrwdt,nop

22. What are the commonly reoccurring sequences of instructions in PIC microcontroller?

The either-or sequence, decrement of 16 bit counter and testing a 16 bit variable for zero.

23. What is data memory?

Data Memory is also known as Register File. Register File consists of two components.
1. General purpose register file (same as RAM).
2. Special purpose register file (similar to SFR in 8051).
The special purpose register file consists of input/output ports and control registers

24. What is FSR Register?

FSR Register (File Selection Register, address = 04H, 84H) FSR is an 8-bit register used as data
memory address pointer. This is used in indirect addressing mode.

32
25. What is the purpose of INDF register?

INDF Register (INDirect through FSR, address = 00H, 80H) INDF is not a physical register. Accessing
INDF access is the location pointed to by FSR in indirect addressing mode.

26. What is PCL register?

PCL Register (Program Counter Low Byte, address = 02H, 82H) PCL is actually the lower 8-bits of
the 13-bit program counter. This is a both readable and writable register.

27. Briefly explain PCLATH register?

PCLATH Register (Program Counter Latch, address = 0AH, 8AH) PCLATH is a 8-bit register which
can be used to decide the upper 5bits of the program counter. PCLATH is not the upper 5bits of the
program counter. PCLATH can be read from or written to without affecting the program counter.
The upper 3bits of PCLATH remain zero and they serve no purpose. When PCL is written to, the
lower 5bits of PCLATH are automatically loaded to the upper 5bits of the program counter

28. What are the limitations of PIC Microcontroller?

The PIC architectures have several limitations:


 Only one accumulator
 A small instruction set
 Operations and registers are not orthogonal; some instructions can address RAM and/or
immediate constants, while others can only use the accumulator
 Memory must be directly referenced in arithmetic and logic operations, although indirect
addressing is available via 2 additional registers
 Register-bank switching is required to access the entire RAM of many devices

29. Describe the working of ADDLW instruction.

33
30. Describe the working of ADDWF instruction.

UNIT II INTERRUPTS AND TIMER

34
SYLLLABUS TOPICS
PIC micro controller Interrupts

a. External Interrupts-Interrupt Programming–Loop time subroutine


b. Timers-Timer Programming
c. Front panel I/O-Soft Keys– State machines and key switches
d. Display of Constant and Variable strings.

ANNA UNIVERSITY QUESTIONS (UQ)


NOV/DEC 2016

1. Explain the functionality of TIMER for PIC Microcontroller with a suitable program.
2. What is Interrupt? Explain the Interrupt structure of PIC Microcontroller with neat diagram.

OTHER POSSIBLE QUESTIONS (Q)

a. External Interrupts-Interrupt Programming–Loop time subroutine

1. Explain the Interrupt structure of PIC16C7X

2. Write the subroutines needed for setting up LoopTime Subroutine and its Interrupt Service
Routine.
3. Explain INTSERVICE, the Interrupt Service Subroutine with suitable program.

4. Q4. Briefly Explain LoopTime subroutine.

b. Timers-Timer Programming

5. Explain the Timer Modules in PIC microcontroller

c. Front panel I/O-Soft Keys– State machines and key switches

6. Explain the KeySwitch subroutine algorithm with flowchart

7. Explain the keypad and keyswitch interface.

d. Display of Constant and Variable strings.

8. Explain the display of constant and variable strings using suitable program

35
QUESTIONS AND ANSWERS

UQ1. Explain the functionality of TIMER for PIC Microcontroller with a suitable program.
( Nov.Dec2016)

Timer-0 The Timer 0 module is a simple 8-bit overflow counter. The clock source can be either the
internal clock (fosc/4) or an external clock. When the clock source is an external clock, the Timer-0
module can be selected to increment on either the rising or falling edge.

Timer-0 module also has a programmable prescalar option. This prescalar can be assigned either to
Timer 0 or the watchdog Timer.
The counter sets a flag TOIF when it overflows and can cause an interrupt at that time if that
interrupt source has been enabled (TOIF=1). Timer 0 can be assigned an 8-bit prescalar that can
divide the input by 2,4,8,16,...,256. Writing to TMRO resets the prescalar assigned to it.
Timer-0, or its prescalar can be connected to either of two input sources.
1. fosc/4
2. RA4/ TOCKI, the input connected to bit 4 of PORTA.

The Timer-0 Counter sets a flag T0IF (Timer-0 Interrupt Flag) when it overflows and can cause an interrupt
at that time if that interrupt source has been enabled, (T0IE = 1), i.e., timer-0 interrupt enable bit = 1.
OPTION Register Configuration :
Option Register (Addr: 81H) Controls the prescaler and Timer -0 clock source. The following OPTION
register configuration is for clock source = fosc /4 and no Watchdog timer.

36
Timer-0 use without pre-scalar
Internal clock source of f osc /4. (External clock source, if selected, can be applied at RA4/TOCKI input at
PORTA). The following diagram shows the timer use without the prescaler.

37
The following simple program creates a delay of 1 sec using Timer0:

38
Timer-1 Module
The Timer1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H and TMR1L)
which are readable and writable. The TMR1 register pair (TMR1H: TMR1L) increments from 0000H
to FFFFH and rolls over to 0000H. The TMR1 interrupt, if enabled, is generated on overflow which
sets the interrupt flag bit TMR1IF-(PIR< 0 >). This interrupt can be enabled/disabled by setting/
clearing TMR1 interrupt enable bit TMR1IE-(PIE < 0 >) The operating and control modes of Timer 1
is determined by the special purpose register T1CON.

The following simple program creates a delay of 1 sec using TIMER1:

#include<pic.h>

int Count = 0;
void main (void)
{
T1CON = 0b00000001;
while (1)
{
while (! TMR1IF);
TMR1IF = 0;
Count ++;
if (Count == 15)

39
{
Count = 0;
}
}
}

Timer 2

Timer 2 is an 8-bit timer with a prescalar and a port sclar. It can be used on the PWM mode of CCP
modules. The TMR2 register is readable and writable and is cleared on any device reset. The input
clock (fosc/4) has a prescalar option of 1:1, 1:4 or 1:16 selected by bits 0 and 1 of T2CON register.
The timer 2 module has a 8-bit period register (PR2). timer 2 increments from 00H until it matches
PR2 and then resets to 00H on the next increment cycle. PR2 is a readable and a writable register.
PR2 is initialized to FFH on reset.
The output of TMR2 goes through a 4-bit post scalar (1:1, 1:2 to 1:16) to generate a TMR2 interrupt
by setting TMR2IF flag.
The following simple C language program creates a delay of 1 sec using TIMER2:

UQ2. What is Interrupt? Explain the Interrupt structure of PIC Microcontroller with neat
diagram. ( Nov/ Dec 2016)
Q1. Explain the Interrupt structure of PIC16C7X

ANSWER:

Interrupt is the signal sent to the micro to mark the event that requires immediate attention.
Interrupt is requesting the processor to stop to perform the current program and to make time to
execute a special code. In fact, the method of interrupt defines the option to transfer the
information generated by internal or external systems inside the micro by them self! Once the
system has finished the task imposed on it, the processor will be notified that it can access and
receive the information and use it.

40
The request for the microcontroller to free itself to execute the interrupt could come from several
sources:

 External hardware devices. Common example is pressing on the key on the keyboard, which
causes to the keyboard to send Interrupt to the microcontroller to read the information of the
pressed key.
 The processor can send interrupts to itself as a result of executing the program, to report an
error in the code. For example, division by 0 will causes an interrupt.
 In the multi-processor system, the processors can send to each other interrupts as a way to
communicate.

There are two types of PIC interrupts:

Software interrupts - come from a program that runs by the processor and request the processor
to stop running the program, go to make an interrupt and then to return to continue to execute the
program.
An example: Procedure - when there is a procedure call, the processor stops the execution of the
program, jumps to the place in memory that reserved for a procedure executes the procedure and
only then returns back to the program and continues to execute.

Hardware interrupts -these are sent to microcontroller by hardware devices as a third-party;


some of them can be blocked - (masking) by Interrupt Enable bit (IE). When the interrupt is
requested the PIC microcontroller does not "see" the request for the interrupt and will not execute
it. In fact the blocked interrupt will not be executed until it will be unblocked.
For example: The processor is in the middle of a calculation, and we do not want to write into
memory until the micro did not finish the calculation. In this situation, we will block the "write to
the memory" interrupt. We will unblock the interrupt only after the processor finished the
calculation, thus preventing him to write into the memory as long as it is in the middle of the action.
There are some interrupts that can not be mask / blocked NMI - Non Mask able Interrupts. They are
used to report on critical hardware issues, such as the drop of voltage. In this situation we are
interested in immediate response from the processor without the ability to ignore them.

41
The settings of the interrupts are done by using 3 interrupt control registers:
 INTCON . This register contains the status of the high-priority interrupts and general definitions.

 PIE (PIE1, PIE2) This register contains the interrupt enabling bits of the low-priority interrupts.
 PIR (PIR1, PIR2) This register contains the interrupt flags of the low-priority interrupts.

42
43
44
Q2. Write the subroutines needed for setting up Loop Time Subroutine and its Interrupt
Service Routine.

45
46
Q3. Explain IntService, the Interrupt Service Subroutine with suitable program.

47
48
Q4. Briefly Explain LoopTime subroutine.

49
Q5.Explain the Timer Modules in PIC microcontroller

Answer

Timer Modules
Timer-0 The Timer 0 module is a simple 8-bit overflow counter. The clock source can be either the
internal clock (fosc/4) or an external clock. When the clock source is an external clock, the Timer-0
module can be selected to increment on either the rising or falling edge.
Timer-0 module also has a programmable prescalar option. This prescalar can be assigned either to
Timer 0 or the watchdog Timer.
Timer-0 The Timer 0 module is a simple 8-bit overflow counter. The clock source can be either the
internal clock (fosc/4) or an external clock. When the clock source is an external clock, the Timer-0
module can be selected to increment on either the rising or falling edge.

Timer-0 module also has a programmable prescalar option. This prescalar can be assigned either to
Timer 0 or the watchdog Timer.
The counter sets a flag TOIF when it overflows and can cause an interrupt at that time if that
interrupt source has been enabled (TOIF=1). Timer 0 can be assigned an 8-bit prescalar that can
divide the input by 2,4,8,16,...,256. Writing to TMRO resets the prescalar assigned to it.
Timer-0, or its prescalar can be connected to either of two input sources.
1. fosc/4
2. RA4/ TOCKI, the input connected to bit 4 of PORTA.

The Timer-0 Counter sets a flag T0IF (Timer-0 Interrupt Flag) when it overflows and can cause an interrupt
at that time if that interrupt source has been enabled, (T0IE = 1), i.e., timer-0 interrupt enable bit = 1.
OPTION Register Configuration :
Option Register (Addr: 81H) Controls the prescaler and Timer -0 clock source. The following OPTION
register configuration is for clock source = fosc /4 and no Watchdog timer.

50
The counter sets a flag TOIF when it overflows and can cause an interrupt at that time if that
interrupt source has been enabled (TOIF=1). Timer 0 can be assigned an 8-bit prescalar that can
divide the input by 2,4,8,16,...,256. Writing to TMRO resets the prescalar assigned to it.
Timer-0, or its prescalar can be connected to either of two input sources.
1. fosc/4
2. RA4/ TOCKI, the input connected to bit 4 of PORTA.

Timer 0 Operation without prescaler (PSA=1)


Option Register (Addr: 81H)

Timer 0 Operation with prescaler (PSA=0)

51
Timer-1 Module
The Timer1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H and TMR1L)
which are readable and writable. The TMR1 register pair (TMR1H: TMR1L) increments from 0000H
to FFFFH and rolls over to 0000H. The TMR1 interrupt, if enabled, is generated on overflow which
sets the interrupt flag bit TMR1IF-(PIR< 0 >). This interrupt can be enabled/disabled by setting/
clearing TMR1 interrupt enable bit TMR1IE-(PIE < 0 >) The operating and control modes of Timer 1
is determined by the special purpose register T1CON. Timer1 can be enabled / disabled by setting /
clearing control bit TMR1ON in T1CON register.

T1CON (10H)

52
Timer 1 can operate in one of the two modes.
• As a timer. (TMR1CS = 0)

53
In timer mode, Timer 1 increments in every instruction cycle. The Timer 1 clock source is fosc/4.
Since the internal clock is selected, the timer is always synchronized and there is no further need of
synchronization.
• As a counter (TMR1CS = 1)
In counter mode, it increments on every rising edge of the external clock input.

Use of Timer-2
Timer 0: 8-bit timer/counter with 8-bit prescalar
Timer 1: 16-bit timer/counter with prescalar, can be incremented during sleep
via external crystal/clock.
Timer 2: 8-bit timer/counter with 8-bit period register, prescalar, post scalar.

54
Timer 2 Circuitry

55
Timer 2 is an 8-bit timer with a prescaler and a portscaler. It can be used on the PWM mode of CCP
modules. The TMR2 register is readable and writable and is cleared on any device reset. The input
clock (fosc/4) has a prescalar option of 1:1, 1:4 or 1:16 selected by bits 0 and 1 of T2CON register.
The timer 2 module has a 8-bit Period Register (PR2). Ttimer 2 increments from 00H until it
matches PR2 and then resets to 00H on the next increment cycle. PR2 is a readable and a writable
register. PR2 is initialized to FFH on reset.
The output of TMR2 goes through a 4-bit post scalar (1:1, 1:2 to 1:16) to generate a TMR2 interrupt
by setting TMR2IF flag.

56
Q6. Explain CCP module in detail.

CCP MODULE – Capture / Compare / PWM (CCP ) Module

57
58
59
60
61
62
63
Application of PWM using CCP module:

The DC motor drive circuit use a number expressed in sign-plus-magnitude for control purpose. The sign
of the number, emited on bit 7 of PORTD, determines the direction of current through the motor . When
bit 7 is high and the PWM output is turned on , the driver on the left is switched on to Vmotor while the
driver on the right is switched on to 0 volts and current flows from left to right through the motor. When
bit 7 is low and the PWM output is turned on just the opposite is true and current flows from right to
left through motor. When the PWM output is off, the current in the dc motor coasts through the diodes
built into half H drivers. By controlling the duty cycle of the PWM output , the average current in the dc
motor is controlled.

64
65
Q7. Explain the Keypad / Keyswitch interface and subroutine algorithm with flowchart

Front-Panel I/O :

Design of instruments and other devices that requires interactions often an LCD alphanumeric display
plus either keyswitches or a rotary pulse generator (RPG) in their design of front panel. The display
serves to display measurements, or other outputs, results. The also combines with the keyswitchs or the
RPG for the entry of parameters. For example, so the user can see successive digit entries combine and
form the desired amplitude. An RPG offers the desirable feature of being able to increment or
decrement the value of parameter being displayed on the LCD

Matrix Keypad is a very useful and user friendly when we want to design certain applications like
Calculator, Telephone etc. Matrix Keypad is made by arranging push button switches in rows and
columns. To interface a 4*4 (16 keys) matrix keypad with a microcontroller, 16 pins of a microcontroller
are needed.

Pressed keys can be detected by Scanning. For the sake of explanation, lets assume all column
connections (Col1 – Col4) are input pins and all row connections (Row1 – Row4) are output pins. In the
normal case (not scanning) all column inputs where in LOW (GND) state. For scanning keypad,

66
1. A Logic HIGH signal is given to Col1 of column inputs.
2. Then each Row output (row1 – row4) is scanned one by one. If any of the key belongs to first
column is pressed, the Logic high signal from the Col1 will pass to that row. Through we can
detect the key.
3. This process is repeated for all columns if we want to detect multiple keys.

Matrix Keypad scanning is stopped as soon as any key press is detected and the Scanning is restarted if
we need more inputs.

Soft Keys:
A multiple line LCD display presents the opportunity, show in the figure

of being used with miniature pushbutton switches that are aligned to the right of each line of the
display. The label for each switch can be displayed, and change at the right edge of row corresponding
to that switch. The keypad interface circuit illustrate how the four soft keys can be treated in the same
manner as the 12keys of keypad. Infact , key switches are generally grouped into array such as this
whether or not they are physically grouped together in a keypad . The keypad interface figure below
shows a pin from a seprate port (bit 7 of PORTD) being used to derive the coloum of softkeys. If bit 0 of
PORTB is not used as an interrupt input. Then it actually makes sense to use that pin to drive the column
of softkeys.

67
Matrix Keypad is connected to the PORTB of the PIC Microcontroller. Each column of the Matrix Keypad
is connected to RB0 – RB3 of the PIC Microcontroller, which are configured as output pins. While each
row of the Matrix Keypad is connected to RB4 – RB7 of the PIC Microcontroller, which are configured as
input pins.

Keypad and Softkey Interface

State Machines and key switches

Key switches are not changed very fast. They can be checked once each time around the mainloop in a
keyswitch subroutine. Looptime of of 10ms was selected because the maximum keybounce time of most
of the mechanical keyswitches is less than 10ms. Consequently, if keyswitch detects that a key is newly
pressed, it can be assured that the next time is called, 10ms later, any erratic bouncing of the key
contacts will have settled out, with the contacts firmly closed. The press and relese of a keyswitch occurs
over an interval of many tens of millisecounds. For example, if a keyswitch is pressed and released at the

68
relatively fast rate of four timesa second. The switch may be closed for 12 looptimes, open for 12
looptimes, closed for 12 looptimes, etc.
The keyswitch subroutine will use a state variable call KEYSTATE to keep track, from one call to the next
, of the sequencing of the following task
1. Debounce the keyswitch
2. Determined which key is pressed
3. Take appropriate action once for that press of the key
4. Wait for the relese of that key

Key switch flowchart

69
The keyswitch algorithm test the STATUS register Z bit upon returning from the AnyKey subroutine if
Z=1, a return from the keyswitch subroutine occurs. On the other hand if Z=0, a key is newly pressed , so
KEYSTATE is incremented to H’01’ before returning from the subroutine Ten milisecound later the
keyswitch subroutine is reentered, this time KEYSTATE = H’01’ if a key is press was detected lastime. By
now any keybounce has settled out. A scankey subroutine is called it returns with Z=1 and a KEYCODE
RAM variable loaded with a value that identifies the pressed key. If for any reson it cound not identifiy
the press key. It returns with Z=0 in the satus register.
A table driven implementation of the scankey subroutine is listed to test the 16 keys in the order of their
keycode value
0,1,2,3….15 for ach value, a corresponding table entry is taken from Scankeys_table. The lower 4 bits of
table entry are used to drive the column of the selected key low and the other columns high. In this way
the only keys that can drive one of the 4 upper bits of PORTB low are the four keys in the selected
column. The scankeys subroutine matches what is read back from the upper 4 bits of PORTB against the
upper 4 bits of the table entry. If a match does occur, the next key is checked. If a match does not occur
for any of the 16 keys, the subroutine returs with Z=0.
The 220Ω resistors protect the PIC’s output drivers during the execution of scankeys if two key switchs
in the same row are pressed simultaneously. In this abnormal case, two output drivers will be shorted
together. A high output will be shorted to a low output during the testing of half of the keys, the
220Ωresistors limit the current to less than 10mA when this happens.
Upon the return from the scankeys subroutine, the keyswitch subroutine tests the STATUS register Z bit
if Z=1 it increments KEYSTATE and returns, prepard to act on the pressed key in 10ms. If Z=0 then
somehow scankeys failed to identify a pressed key. This might occur if, for example, two keys in the
same column are pressed simultaneously. In that case, there will be no entry in scankey_table that
matches what is read from PORTB, however this failure occurs, KEYSTATE is cleared to zero, starting
over again in the hunt for pressed key When KeySwitch is called with KEYSTATE=H’02’, it increments
KEYSTATE. If it then does a instruction, the job of this KeyAction subroutine is to carry out the proper
response for the pressedkey. The return from KeyAction will pop the return address and actually
execute a return from KeySwitch(if KeyAction was accessed with a goto instruction instead of call
instruction).
The last two states of the KeySwitch algorithm require the pressed key to be released during two
successive passes around the mainline loop. This overcomes any potential problem with keybounce time
during the release key.

AnyKey Subroutine determine if any key is pressed

70
71
72
Q8. Explain the display of constant and variable strings using suitable program.

Display Pus RPG use:

A popular display plus input device combination is show in the figure 8.5. the grayhill rotary pulse
generator its feature is 24 detected position per revolution so it clicks from one position to the next,
giving the feel of rotary switch . it is also features an integral momentary action push button switch.
When used with an alphanumeric display such as show in the figure 8.5 the RPG’s knob can be pushed
and released to cycle the display among an instruments setup parameters as well as its measurements
results. Stopping at specific setup parameters (ex: voltage amplitude of function generator) the RPG can
then be rotate to increase or decrease the value of parameter. Detents support this function by helping
a user to avoid inadvertently changing setup parameters while cycling among them with successive
pushes of knob

The PIC interface for grayhill RPG show in the figure 8.6b. The momentary action push button switch can
be treated in the same way as one of the soft keys figure 8.2. then it will be checked, debounce, and
handled at regular intervals of time. The two RPG output must be treated differently from keyswitches
since the information they convey is represented by two output levels and their changes. They must also
treated differently from RPG interface. Any one RPG output as in PB0/INT interrupt input. In the case of
grayhilll RPG, action is needed whenever either output change, not just when one of the output riseing

73
edge. The two RPG output can be checked in an RPG subroutine, called from the mainline loop[. The two
inputs are compared with their values 10ms ago. The selected parameter be incremented or
decremented if the input have change.

Display of variable string:


When entering setup parameter with either a keypad or an RPG and when displaying the results of an
instrument measurement, it is necessary to write a string of ASCII-code characters to display. Since the
character vary, they are taken from the RAM. The assignment of a string variable VSTRING, to RAM
with microchip’s MPASM assembler is illustrated. Assume that a display string has the format
1. Cursor position code (Figuer 7.8)
2. ASCII string of characters to be displayed
3. Endof string designator,H’00’

74
Variable display string

VSTRINGlength equ 12

75
(Refer example program in pg 167 –John B. Peatman)

Given string having this format, a DisplayV subroutine can be written to send the first character to the
LCD display as a command (RS=0) and subsequent characters as displayable characters (RS=1) and to
stop when H’00’ is accessed. If the maximum number of every character to be sent to the display from
the string is 10, then 12 RAM location must be reserved for the 10 displayable characters, the leading
cursor position code, and the trailing end of string designator. This reservation of RAM for a string called
VSTRING is illustrated, the MPASM assembler permits code writers to create error message to warn of
error producing condition.

Display of Character and its ASCII Code

76
LCD Display Circuit

Steps to write a subroutine to display any variable string pointed by indirect addressing pointer

Display of Constant String

Constant string arise in seven ways. The labels associated with softkeys represent one application. The
units(kHz) associate with the variable represent another. In this section a DisplayC subroutine that
makes use of display string stored in program memory will be developed. Each byte of each string is
accessed via retlw instruction in the process of returning from DisplayC_table subroutine. In PIC ay of
storing tables and string in program memory and subsequently accessing them with a variable poiinter

77
The source code form of display string store in program memory can be illustrate by the following
example used to display the string

ROW4Coll

Being in the first character position of the fourth row of the LCD display
_ROW4Coll

retlw H’D4’ ;cursor postioning code (figure 7.8)


dt “ROW4Coll” ;Character to be displayed
retlw 0
He dt assembler directive provides a convenient way of creating ASCII string,
the MPASM assembler converts dt “ROW4Coll” to
retlw A’R’
retlw A’O’
retlw A’W’
retlw A’4’
retlw A’C’
retlw A’o’
retlw A’l’
retlw A’l’

where A’R’ represented the ASCII code for the letter R the label for this sequence of retlw instruction
uses the initial underline character to serves as a remainder that entities such as this represented label
for constant string display. In fact the constant string itself can be used as its own label Figuer 8.8 shows
the DisplayC_Table subroutine to be locate in the first 256 address of the program area along with the
other table subroutine. It include every constant string display needed for an application, one right after
another. To get the specific display string , the DisplayC subroutine needs to have passed to it the offsert
from the instruction following addwf PCL,F this instruction to start of the specific display string of
interest.
The offset in the code is loaded to W before DisplayC subroutine is called when the DisplayC_Table
subroutine is called by the DisplayC subroutine, it will add W to the address represented by CDS, loading
the program counter with the results. Consequently it will return with W loaded by select retlw
instruction there by passing back to DisplayC the first byte from the selected display string.

78
79
80
TWO MARK QUESTIONS AND ANSWERS

UNIT - II

1. What are the Timers available in PIC 16c6x/7x series?

The Timers available in PIC 16c6x/7x series are Timer 0, Timer 1 and Timer2.

2. What are the features of Timer 0?

The Timer 0 module is a simple 8-bit overflow counter. The clock source can be either the internal
clock (fosc/4) or an external clock. When the clock source is an external clock, the Timer-0 module
can be selected to increment on either the rising or falling edge.Timer-0 module also has a
programmable prescalar option.

3. Give the bit configuration of Timer 0.

3. What are the features of Timer 1?


The Timer1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H and TMR1L)

which are readable and writable. The TMR1 register pair (TMR1H: TMR1L) increments from 0000H
to FFFFH and rolls over to 0000H. The TMR1 interrupt, if enabled, is generated on overflow which
sets the interrupt flag bit TMR1IF

4. Give the bit configuration of Timer 1.

81
5. Explain the features of Timers used in PIC 16c6x/16c7x?

Timer 0: 8-bit timer/counter with 8-bit prescalar

Timer 1: 16-bit timer/counter with prescalar, can be incremented during sleep

via external crystal/clock.

Timer 2: 8-bit timer/counter with 8-bit period register, prescalar, post scalar.

6. What is the CCP module?


The CCP module(s) can operate in one of the three modes: 16-bit capture, 16-bit compare, or upto
1-bit Pulse Width Modulation (PWM).

7. What are the Timer resources for CCP modes?

8. Which is the primary external interrupt input in a PIC microcontroller?

RB0/INT, bit 0 of PORTB is the primary external interrupt input in a PIC microcontroller

82
9. Which bit permits to setup the interrupt input to generate an interrupt on rising/falling edge?

INTEDG bit of OPTION _REG permits to setup the interrupt input to generate an interrupt on
rising/falling edge

10. How to calculate the maximum PWM resolution?

The maximum PWM resolution can be calculated using

11. State the Interrupt control registers.

The settings of the interrupts are done by using 3 interrupt control registers: INTCON, PIE and PIR
 INTCON . This register contains the status of the high-priority interrupts and general definitions.

 PIE (PIE1, PIE2) This register contains the interrupt enabling bits of the low-priority interrupts.
 PIR (PIR1, PIR2) This register contains the interrupt flags of the low-priority interrupts.

12. What is the bit configuration of INTCON register?

GIE: The Global Interrupt Enable bit is like the master switch for all the different interrupts.
EEIE: EE Write Complete Interrupt Enable bitEE Write Complete Interrupt Enable bit allows an
interrupt to occur when a write operation to the EEPROM has completed.
T0IE: The TMR0 Overflow Interrupt Enable bit allows an interrupt when the TMR0 counter
overflows from 255 (0xff) to 0 (0x00).
INTE: The RB0/INT External interrupt Enable bit allows an interrupt from a clocking signal applied
to pin RB0.
RBIE: The Port Change Interrupt Enable bit allows an interrupt when there is a change of state on
pins RB7, RB6, RB5 and RB4 on PORTB.
T0IF: The TMR0 Overflow Interrupt Flag bit is used by the device to indicate if the interrupt was
the result of a TMR0 overflow.
INTF: The RB0/INT External Interrupt Flag bit is used by the device to indicate if the interrupt was
the result of a clocking signal on the RB0 pin.
RBIF: The Port Change Interrupt Flag bit is used likewise by the device to indicate if the interrupt
was the result

12. Give the block diagram for capture mode of operation.


Capture mode captures the 16-bit value of TMR1 into CCPRxH: CCPRxL register pair. The capture
event can be programmed for either the falling edge, rising edge, fourth rising edge, or the sixteenth
rising edge of the CCPx pair.

83
13.Briefly explain compare mode of operation.
Compare mode compares the TMR1H: TMR1L register pair to the CCPRxH: CCPRxL register pair.
When a match occurs an interrupt can be generated, and the output pin CCPx can be forced to given
state (High or Low), TMR1 can be reset (CCP1) or TMR1 reset and start A/D conversion (CCP2).
This depends on the control bits < CCPxM3 : CCPxM0>

14. What is PWM mode of operation?

PWM mode compares the TMR2 register to a 10 bit duty cycle register (CCPRxH : CCPRxL<5:4>) as
well as an 8-bit period register (PR2). When the TMR2 register= Duty cycle register, the CCPx pin
will be forcred low. When TMR2=PR2, TM2 is cleared to 00H, an interrupt can be generated, and
the CCPx pin, if programmed in the O/P mode, will be forced high.

84
15. How is the PWM time period calculated?

16

17.

85
18.

Timer Calculations and Program:

1. TIMER 0

Calculating Count, Fout, and TMR0 values

If using INTERNAL crystal as clock, the division is performed as follow:

86
PIC TIMER0 formula for internal clock

Fout– The output frequency after the division.

Tout – The Cycle Time after the division.

4 - The division of the original clock (4 MHz) by 4, when using internal crystal as clock (and not
external oscillator).
Count - A numeric value to be placed to obtain the desired output frequency - Fout.
(256 - TMR0) - The number of times in the timer will count based on the register TMR0.

An example of INTERNAL crystal as clock

Suppose we want to create a delay of 0.5 second in the our program using Timer0. What is the value
of Count?

Calculation:
First, let’s assume that the frequency division by the Prescaler will be 1:256. Second, let’s set
TMR0=0. Thus:

Formula to calculate Cout using Timer0

If using EXTERNAL clock source (oscillator), the division is performed as follow:

PIC TIMER0 formula for external clock

In this case there is no division by 4 of the original clock. We use the external frequency as it is.

87
An example of EXTERNAL clock source (oscillator):

What is the output frequency - Fout, when the external oscillator is 100kHz and Count=8?

Calculation:
First, let’s assume that the frequency division by the Prescaler will be 1:256. Second, let’s set
TMR0=0. Thus:

Formula to calculate Fout for Timer0

Delay of 1 sec using Timer0

The following simple program creates a delay of 1 sec using Timer0:

1 sec delay using Timer0

88
2. TIMER 1

Calculating Count, Fout, and Timer1 values

If using INTERNAL crystal as clock, the division is performed as follow:

PIC TIMER1 formula for internal clock

If using EXTERNAL clock source (oscillator), the division is performed as follow:

PIC TIMER1 formula for external clock

Simple example and calculation of how to use TIMER1:

Suppose we want to create a delay of 2 second in the our program using Timer1. What is the value of
Count?

Calculation:
First, let’s assume that the frequency division by the Prescaler will be 1:1. Second, let’s set TMR1=0,
which means the TMR1 will count 65,536 times. Thus:

Formula to calculate Cout for Timer1

Delay of 1 sec using Timer1

The following simple program creates a delay of 1 sec using TIMER1:

89
#include<pic.h>

int Count = 0;
void main (void)
{
T1CON = 0b00000001;
while (1)
{
while (! TMR1IF);
TMR1IF = 0;
Count ++;
if (Count == 15)
{
Count = 0;
}
}
}

1 sec delay using Timer1

3. TIMER 2
How to calculate the required values of the TIMER2:

Fout – The output frequency after the division.


Tout – The Cycle Time after the division.
4 - The division of the original clock (4 MHz) by 4, when using internal crystal as clock (and not
external oscillator).
Count - A numeric value to be placed to obtain the desired output frequency - fout.
(PR2 – TMR2) - The number of times the counter will count.

Simple example and calculation of how to use TIMER2:

Suppose we want to create a delay of 1 second in the our program using Timer2. What is the value of
Count?

Calculation:

First, let's assume that the frequency division by the Prescaler will be 1:1 and Postscaler will be 1:16.
Second, let's set TMR1=0 and PR2=255. Thus:

90
The following simple C language program creates a delay of 1 sec using TIMER2:

91

You might also like