0% found this document useful (0 votes)
64 views

Unit 2

The document discusses interrupts and timers for PIC microcontrollers. It describes the differences between polling and interrupts, the types of interrupts for PICs including external, software and hardware interrupts. It provides details on interrupt registers and flags for the PIC16C6X family. Interrupts sources for the PIC include the INT pin, timer 0 overflow, PORTB change, and peripherals. Timers include timer 0 and the watchdog timer.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Unit 2

The document discusses interrupts and timers for PIC microcontrollers. It describes the differences between polling and interrupts, the types of interrupts for PICs including external, software and hardware interrupts. It provides details on interrupt registers and flags for the PIC16C6X family. Interrupts sources for the PIC include the INT pin, timer 0 overflow, PORTB change, and peripherals. Timers include timer 0 and the watchdog timer.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

UNIT II

INTERRUPTS AND TIMER


PIC micro controller Interrupts- External Interrupts-Interrupt Programming–
Loop time subroutine – Timers-T7imer Programming– Front panel I/O-Soft
Keys– State machines and key switches– Display of Constant and Variable
strings.

PIC Microcontroller Interrrupts:

Introduction:

There are 2 methods for communicating between the microcontroller and


the external system:

 POLLING
 INTERRUPTS

POLLING

Using this method, the microcontroller accesses at the exact time interval
the external device, and gets the required information. The user is the one
who determines the time intervals in which micro “contacts” the device.
In the Polling method, the PIC microcontroller must "access by himself" the
device and “ask” for the information it needs for processing. In fact we see
that in the Polling method the external devices are not independent systems;
they depend on the microcontroller, and only the micro is entitled to obtain
access to the information it needs. The main drawback of this method when
writing program is waste of time of microcontroller, which needs to wait and
check whether the new information has arrived.

INTERRUPTS

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.

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 “blocked”, 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 “masked”/”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.

Interrupts in PIC16C6X:

The PIC16C6X family has up to 11 sources of interrupt. The interrupt


control register (INTCON) records individual interrupt requests in flag bits. It
also has individual and global interrupt enable bits.

PICmicro MCUs can have many sources of interrupt. These sources


generally include one interrupt source for each peripheral module, though
some modules may generate multiple interrupts (such as the USART
module). The current interrupts are:

• INT Pin Interrupt (external interrupt)

• TMR0 Overflow Interrupt

• PORTB Change Interrupt (pins RB7:RB4)

• Comparator Change Interrupt

• Parallel Slave Port Interrupt

• USART Interrupts

• Receive Interrupt

• Transmit Interrupt

• A/D Conversion Complete Interrupt

• LCD Interrupt.

• Data EEPROM Write Complete Interrupt

• Timer1 Overflow Interrupt

• Timer2 Overflow Interrupt

• CCP Interrupt

• SSP Interrupt

There is a minimum of one register used in the control and status of the
interrupts. This register is: INTCON

Global interrupt enable bit, GIE (INTCON) enables (if set) all un-masked
interrupts or disables (if cleared) all interrupts. When bit GIE is enabled,
and an interrupt flag bit and mask bit are set, the interrupt will vector
immediately. Individual interrupts can be disabled through their
corresponding enable bits in the INTCON register. GIE is cleared on reset.

The “return from interrupt” instruction, RETFIE, exits the interrupt routine
as well as sets the GIE bit, which re-enable interrupts. The RB0/INT pin
interrupt, the RB port change interrupt and the TMR0 overflow interrupt
flag bits are contained in the INTCON register. The peripheral interrupt flag
bits are contained in special function registers PIR1 and PIR2. The
corresponding interrupt enable bits are contained in special function
registers PIE1 and PIE2 and the peripheral interrupt enable bit is contained
in special function register INTCON. When an interrupt is responded to, bit
GIE is cleared to disable any further interrupts, the return address is
pushed onto the stack and the PC is loaded with 0004h. Once in the
interrupt service routine the source(s) of the interrupt can be determined by
polling the interrupt flag bits. The interrupt flag bit(s) must be cleared in
software before re-enabling interrupts to avoid recursive interrupts. For
external interrupt events, such as the RB0/INT pin or RB port change
interrupt, the interrupt latency will be three or four instruction cycles. The
exact latency depends when the interrupt event occurs The latency is the
same for one or two cycle instructions. Once in the interrupt service routine
the source(s) of the interrupt can be determined by polling the interrupt flag
bits. The interrupt flag bit(s) must be cleared in software before re-enabling
interrupts toavoid infinite interrupt requests. Individual interrupt flag bits
are set regardless of the status of their corresponding mask bit or the GIE
bit.
Fig: INTERRUPT LOGIC FOR PIC16Cxx

INT INTERRUPT:

External interrupt on RB0/INT pin is edge triggered: either rising if edge


select bit INTEDG (OPTION) is set, or falling, if bit INTEDG is clear. When a
valid edge appears on the RB0/INT pin, flag bit INTF (INTCON) is set. This
interrupt can be disabled by clearing enable bit INTE (INTCON). The INTF bit
must be cleared in software in the interrupt service routine before re-
enabling this interrupt. The INT interrupt can wake the processor from
SLEEP, if enable bit INTE was set prior to going into SLEEP. The status of
global enable bit GIE decides whether or not the processor branches to the
interrupt vector following wake-up. See Section 13.8 for details on SLEEP
mode.

TMR0 INTERRUPT:
An overflow in the TMR0 register will set flag bit T0IF. The interrupt can
be enabled/disabled by setting/clearing enable bit T0IE.
PORTB INTERRUPT ON CHANGE:
An input change on PORTB sets flag bit RBIF. The interrupt can be
enabled/disabled by setting/clearing enable bit RBIE.
WATCH DOG TIMER (WDT):
The Watchdog Timer is a free running on-chip RC oscillator which does
not require any external components. This RC oscillator is separate from the RC
oscillator of the OSC1/CLKIN pin. That means that the WDT will run, even if
the clock on the OSC1/CLKIN and OSC2/CLKOUT pins of the device has been
stopped, for example, by execution of a SLEEP instruction. During normal
operation, a WDT time-out generates a device reset. If the device is in SLEEP
mode, a WDT time-out causes the device to wake-up and continue with normal
operation. The WDT can be permanently disabled by clearing configuration bit
WDTE.
WDT PERIOD:
The WDT has a nominal time-out period of 18 ms, (with no prescaler).
The time-out periods vary with temperature, VDD and process variations from
part to part (see DC specs). If longer time-out periods are desired, a prescaler
with a division ratio of up to can be assigned to the WDT under software
control by writing to the OPTION register. Thus, time-out periods up to seconds
can be realized.
The CLRWDT and SLEEP instructions clear the WDT and the postscaler, if
assigned to the WDT, and prevent it from timing out and generating a device
RESET condition.
The TO bit in the STATUS register will be cleared upon a WDT time-out.
WDT PROGRAMMING CONSIDERATIONS:
It should also be taken in account that under worst case conditions (VDD =
Min., Temperature = Max., max WDT prescaler) it may take several seconds
before a WDT time-out occurs.
ADC Interrupt
This interrupt is generated when the analog-to-digital conversion ends. This is
only to 16 C7X parts in general. ADIE is the bit that enables this interrupt in
INTCON register. Apart from this the master control bit GIE must be enabled.
The end of the conversion interrupt flag (ADIF) bit is in ADCON0 register.
i. On reset all interrupts are disabled
ii. Programmer Sets/Clears INTEDG bit in OPTION register if Interrupts
are to be recognized on rising/ Falling edge of pulse
iii. Programmer sets in INTCON register GIE and the desired interrupts;
external Interrupt (INT), Timer 0 interrupt ( TOIE), or Port B Change (
RBIE).
iv. On setting the corresponding flag GIE gets disabled (to avoid further
occurrence of interrupt till ISR is executed) and program enters the ISR,
as the program come out of ISR, GIE get enabled automatically.
v. Before RETF the programmer has to disable the corresponding flag of the
interrupt source.
INTCON Register

The INTCON Register is a readable and writable register which contains


various enable and flag bits. Interrupt flag bits get set when an interrupt
condition occurs regardless of the state of its corresponding enable bit or the
global enable bit, GIE (INTCON<7>).This feature allows for software polling.

bit 7 GIE: Global Interrupt Enable bit

1 = Enables all un-masked interrupts

0 = Disables all interrupts

bit 6 PEIE: Peripheral Interrupt Enable bit

1 = Enables all un-masked peripheral interrupts

0 = Disables all peripheral interrupts

bit 5 T0IE: TMR0 Overflow Interrupt Enable bit

1 = Enables the TMR0 overflow interrupt

0 = Disables the TMR0 overflow interrupt

bit 4 INTE: INT External Interrupt Enable bit

1 = Enables the INT external interrupt

0 = Disables the INT external interrupt

bit 3 RBIE (1): RB Port Change Interrupt Enable bit

1 = Enables the RB port change interrupt

0 = Disables the RB port change interrupt

bit 2 T0IF: TMR0 Overflow Interrupt Flag bit


1 = TMR0 register has overflowed (must be cleared in software)

0 = TMR0 register did not overflow

bit 1 INTF: INT External Interrupt Flag bit

1 = The INT external interrupt occurred (must be cleared in software)

0 = The INT external interrupt did not occur

bit 0 RBIF (1): RB Port Change Interrupt Flag bit

1 = At least one of the RB7:RB4 pins changed state (must be cleared


in software)

0 = None of the RB7:RB4 pins have changed state

OPTION_REG Register
The OPTION_REG Register is a readable and writable register, which contains
various control bits to configure the TMR0 prescaler/WDT postscaler (single
assignable register known also as the prescaler), the external INT interrupt,
TMR0 and the weak pull-ups on PORTB.
PIE Register(s)

Depending on the number of peripheral interrupt sources, there may be


multiple Peripheral Interrupt Enable registers (PIE1, PIE2). These registers
contain the individual enable bits for the Peripheral interrupts. These
registers will be generically referred to as PIE. If the device has a PIE
register, The PEIE bit must be set to enable any of these peripheral
interrupts.

Although, the PIE register bits have a general bit location with each register,
future devices may not have consistent placement. Bit location
inconsistencies will not be a problem if you use the supplied Microchip
Include files for the symbolic use of these bits. This will allow the
Assembler/ Compiler to automatically take care of the placement of these
bits by specifying the correct register and bit name.

Interrupt Latency

Interrupt latency is defined as the time from the interrupt event (the
interrupt flag bit gets set) to the time that the instruction at address 0004h
starts execution (when that interrupt is enabled). For synchronous
interrupts (typically internal), the latency is 3TCY. For asynchronous
interrupts (typically external), such as the INT or Port RB Change Interrupt,
the interrupt latency will be 3 - 3.75TCY (instruction cycles). The exact
latency depends upon when the interrupt event occurs (Figure 8-2) in
relation to the instruction cycle. The latency is the same for both one and
two cycle instructions.

INT and External Interrupts

The external interrupt on the INT pin is edge triggered: either rising if the
INTEDG bit (OPTION<6>) is set, or falling, if the INTEDG bit is clear. When a
valid edge appears on the INT pin, the INTF flag bit (INTCON<1>) is set. This
interrupt can be enabled/disabled by setting/clearing the INTE enable bit
(INTCON<4>). The INTF bit must be cleared in software in the interrupt
service routine before re-enabling this interrupt. The INT interrupt can
wake-up the processor from SLEEP, if the INTE bit was set prior to going
into SLEEP. The status of the GIE bit decides whether or not the processor
branches to the interrupt vector following wake-up. See the “Watchdog
Timer and Sleep Mode” section for details on SLEEP and for timing of
wake-up from SLEEP through INT interrupt.
Note: Any interrupts caused by external signals (such as timers, capture,
change on port) will have similar timing.

Context Saving During Interrupts

During an interrupt, only the return PC value is saved on the stack.


Typically, users may wish to save key registers during an interrupt e.g. W
register and STATUS register. This has to be implemented in software. The
action of saving information is commonly referred to as “PUSHing,” while the
action of restoring the information before the return is commonly referred to
as “POPing.” These (PUSH, POP) are not instruction mnemonics, but are
conceptual actions. This action can be implemented by a sequence of
instructions. For ease of code transportability, these code segments can be
made into MACROs (see MPASM Assembler User’s Guide for details on
creating macros).

Interrupt Constrain:

When an interrupt source sends an interrupt signal to CPU, it is saying that


it is ready to be serviced. It is also implying that this servicing needs to
occur in timely manner or else a system malfunction will occur. For
example a PIC chip controlling the operation of a device may use it UART
serial port as an optional port from a personal computer so the PC can
control an arrray of such devices. Alternatively that device may be used in
sand alone mode, with nothing connected to its UART serial port.Give these
two modes of operation , the PIC must be able to rspond to each chracter
recives via the UART and its two-byte FIFO before another two character
arive to overrun the first character. On the other hand, the PIC cannot
dedicate itself solely to waiting for characters to arrive via UART interrupts
because it has ongoing control to do.

The problem posed by UART interrupts is illustrate in the below figure5.1,


show the CPU executing the mainline program (and its subroutine) until a
character is recived by UART. At that point CPU digresses from its execution
of mainline code to execute the UART’s interrupt service routine. Then the
CPU returns to the execution of mainline code. With no other interrupt
occuring, the URAT is serviced as soon as a characterhas been recived and
an interrrupt signal sent to CPU . if the serial data is being transferred at
9600Bd, then these interrupts occur roughly a milisecound apart ,
representedby TPURAT in the below figure 5.1 an deach one is handle
immediately by the CPU
With other interrupt sources enable, the story changes, as illustrate in the
secound figure now the UARTcan recive a character and send an interrupt
signal to the CPU, only to have its service postponed temporarily while the
CPU finishes servicing another interrupt. As can be seen in the figure , an
error may be occasionally occur if care is not taken to keep interrupt service
routines short

For the more general case with multiple interrupt sources, the worst case
sequencing of interrupts must be examined to determine whether a problem
will ever arise. Each interrupt source I, must be characterized by two
parameters

1. The minimum time intervel between interrupts from source I, denoted


by TP

2. The maximum time it takesthe CPU to execute the interrupt sources


handeler subroutine and its call from Intservice denoted by Ti

The minimum time interval between interrupts for a given interrupt source
is determine by the application for example in the case of the 9600Bd UART,
each 8-bit character is farmed between a start bit and a stop bit with a bit
time of 1/9600 secound, each 10-bit frame can arive 10/9600 secound
apart

TPURAT = 10/9600 Secound = 10,000,000/9600 = 1042μs

INTservice Interrupt Service Routine:

When ever an interrupt occurs the CPU automatically pushed the return
address in the program counter onto the stack and clear the GIE(global
interrupt enable) bit, disabling further interrupts. No other register or W are
automatically set aside. Consequently the first job of Intservice is to set
aside the content of W and the SATAUS. Then they can be restored at the
end of the interrupt service routine to exactly the same state they were in
when the interrupt occurred, as required for the proper execution of the
mainline code

This setting aside of W and the SATAUS is illustrated in the first three
instruction of below figure. The assumption is made that the mainline
program will not be switched for direct access of Bank 1 register of RAM
variables at the moment that the interrupts occurs. Once the interrupts
have been enable Bank 1 register and RAM should only be accessed by
indirect addressing.
Fig: IntService interrupt service routine

The three instructions for setting aside W and the SATAUS use

Swapf SATATUS, W

To move the content of SATAUS to W instead of the expected instruction

Movf SATATUS,W

Note that swapf instruction doesnot ever affect the Z bit in the SATATUS
register when it makes this move (even though it copies the upper 4 bits of
SATATUS to the lower 4 bits of W and the lower 4 bits of SATATUS to the
upper 4 bits of W)in contrast the movf instruction corrupt the Z bit restoring
SATATUS and W again the instruction

Swapf W_TEMP,W

Copies W_TEMP to W without affecting the Z bit. It is preceded by

Swapf W_TEMP,F

Which swaps the two halves of W_TEMP so that the following swapf
instruction will swap them again, ending up with every bit of W just where it
was when the interrupt occurred.
The central code of intservice is a sequence of btfsc, call instruction pair.
Each pair test the flag of each enable interrupt source. If the fklag is set, the
source’s interrupt service routine is called that provides the desired
response and clears the flag. If a tested flag is not set, the call is skipped .
this sequence is called polling routine, and quickely get the CPU to the
service routine for the source that requested service

Loop Time Subroutine:

The loop time subroutine is called from the mainline loop,in the case of LED
blink program actually the loop time subroutine to work correctly,the worst
case execution of the remainder of the code in the mainline loop plus the
worst case execution time for all the interrupt service routine that should
request the service. As a consequence successive execution of some task
may occur less than the predefine time like in the Les blinking program. On
the other hand even if this mainline overrun condition dose occur the long
range timing provided by the loop time subroutine will still be accurate
aslong as no counts of scalar are ever lost.

Example:
Looptime
Btfsc SCLAER ,7
Goto looptime
Movlw 5
Addwf SCALER,F
return
External interrupts:

The PIC microcontroller has one pin, RBO/INT that serves as its primary
external interrupt input. This pin is bit 0 of PORTB before initializing the
interrupt circuitry PORTB itself should be initialized. The bit of bank 1
register TRISB set up the corresponding bits of PORTB as either inputs or
outputs. All of the pins that are setup as input pinas optional a weak pullup
resistor is added by clearing the NOT_RBPU bit of OPTION_REG as show in
the figure 6.1b this provides a useful input for a pushbutton switch or for a
array of keyswitches such as keypad show in 6.2a the internal pull-ups of
the circuit in figure 6.2b hold each input pin high until any of the key
switches are pressed, if any of the keyswitch are pressed then the
corresponding column driver drive the output to low.
For example bit 7 of PORTB will be driven low if the key switch labeled “1”
is pressed and if the bit 3 output from PORTB is driven low otherwise the
internal pullup resistor pulls the bit 7 input high

Figure 6.2b also illustrate the use of bit 0 of PORTB as an interrupt input
that can be used independently of the manner in which the other pins of
PORTB are used. the setup for this independent interrupt input show in the
figure 6.3. the presence or absence of the weak pullup resistor on allPORTB
input is irrelevant to this bit0 input since the device that derives this
interrupt pin will override the weak pullup. The INTEDG bit of
OPTION_REG permits us to setup this input to generate an interrupt on
either a rising edge or falling edge. In addition , when used as an interrupt
input, this PB0/INT pin is automatically configured as a Schmitt-trigger
input . Triggering on the input edge regardless of its rise(or fall) time
The INTCON register must be initialized with a one in its INE(RB0/INT
interrupt enable ) bit as well as in its GIE(global interrupt enable) bit . when
the interrupt occure there is no need to read PORTB rather ,just poll the
INTF (Interrupt flag) bit in INTCON to determine if an edge occurring on this
pin is the source of the interrupt if so , then clear the flag with

bcf INTCON,INTF

then service the interrupt and go back to INtservice’s polling routine to look
for any other pending interrupts
OVERVIEW OF TIMER MODULES

The PIC16C72, PIC16C73/73A, PIC16C74/74A, PIC16C76/77 each have


three timer modules. Each module can generate an interrupt to indicate that
an event has occurred (i.e. timer overflow). Each of these modules is
explained in full detail in the following sections.

TIMER MODULES:

There are three completely independent Timers available in PIC 16F8XX


Microcontrollers. They are

 Timer 0

 Timer1

 Timer2
Timer 0:

The Timer 0 module is a simple 8-bit overflow counter. The clock


source can be either the internal system clock (Fosc/4) or an external clock.
When the clock source is an external clock, the Timer0 module can be
selected to increment on either the rising or falling edge.

The Timer 0 module also has a programmable prescaler option. This


prescaler can be assigned to either the Timer0 module or the Watchdog
Timer. Bit PSA assigns the prescalerand bits PS2:PSO determine the
prescaler value. TMR0 can increment at the following rates: 1:1 when the
prescaler is assigned to Watchdog Timer, 1:2, 1:4, 1:8, 1:16, 1:32, 1:64,
1:128 and 1:256.

Synchronization of the external clock occurs after the prescaler. When


the prescaler is used, the external clock frequency may be higher then the
device’s frequency. The maximum frequency is 50 MHz, given the high and
low time requirements of the clock.

Timer 1

Timer1 is the most versatile and can be used to monitor the time
between signal transition occuringon an input pin or control the precise
time of transitions on an output pin. It is a 16-bit timer/counter. The clock
source can be either the internal system clock (Fosc/4), an external clock, or
an external crystal. Timer1 can operate as either a timer or a counter. When
operating as a counter (external clock source), the counter can either
operate synchronized to the device or asynchronously to the device.
Asynchronous operation allows Timer1 to operate during sleep, which is
useful for applications that require a real-time clock as well as the power
savings of SLEEP mode.

Timer 1 also has a prescaler option, which allows TMR1 to increment


at the following rates: 1:1, 1:2, 1:4 and 1:8 TMR1 can be used in
conjunction with the Capture/Compare/PWM module. When used with a
CCP module, Timer1 is the time-base for 16-bit capture or 16-bit compare
and must be synchronized to the device.

Timer 2

Timer 2 is an 8-bit timer with a programmable prescaler and a


programmable postscaler, as well as an 8-bit Period Register (PR2). Timer 2
can be used with the CCP module (in PWM mode) as well as the Baud Rate
Generator for the Synchronous Serial Port (SSP). The prescaler option allows
Timer2 to increment at the following rates: 1:1, 1:4 and 1:16.
The post scaler allows TMR2 register to match the period register
(PR2) a programmable number of times before generating an interrupt. The
postscaler can be programmed from 1:1 to 1:16 (inclusive).

2.2 Overview of Timer Modules :

PIC 16C74A has three modules, viz., Timer-0, Timer-1 and Timer-2. Timer-0
and Timer-2 are 8-bit timers. Timer-1 is a 16-bit timer. Each timer module
can generate an interrupt on timer overflow.

Timer-0 Overview:.

The timer-0 module is a simple 8-bit counter TMR0. Which can be written
to or read from. The counter sets a flag,T0IF, when it overflows and can
causes an interrupt at that time if that interrupt source has been
enable(T0IF=1) Timer0 can be assigned an 8 bit prescaler that can divide
the counter’s input by 2,4,8,16,….256 writing to TMR0 resets the prescaler
assigned to it.

Timer0 or prescaler cab be connected to either of two input sources

1. OSC/4, the PIC’s internal clock

2. RA4/T0CK1, the input connected to bit 4of PORTA

If the prescaler is bypassed and the internal clock used, the circuit is show
in figure6.5 results. The two cycles delay is a result of the need to
synchronize the external clock, TCK1. The internal clock. is write to TMR0
will reset the delay circuit, causing the two cycles that follow the write not to
be counte. Because of these two cycle delay if 256-10 = 246is written to the
TMR0, the T0IF flag will bw set in 12 cycles, no the 10 cycles expected

The use of the prescaler is illustrate in the figure6.6 when OPTION_REG is


initilized as show in the figure timer0 will overflow every 2.048ms (given
OSC=4MHz).

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

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.

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


as follow:

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.

Fig: Timer - 0 operation


Timer - 1 Module

Timer 1 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 (bit-0 of PIR1 register). This interrupt can be
enabled/disabled by setting/clearing TMR1 interrupt enable bit TMR1IE
(bit-0 of the PIE1 register). The operating and control modes of Timer1 are
dete rmined by the special purpose register T1CON. Various bits of T1CON
register are given as follows:-

TMR1 ON : Timer1 ON bit


0 = stops Timer 1; 1 = Enables Timer 1

TMR1CS : Timer 1 Clock source Select Bit


1 = External Clock (RCO/T1OSO/T1CKI)
0 = Inte2rnal Clock ( )

: Timer 1 External Clock Input Synchronization Bit


(Valid if TMR1CS = 1)
1 - Do not synchronize
0 – Synchronize

T1OSCEN: Oscillator enable control bit


1 = Oscillator is enabled
0 = Oscillator is shut off
Timer 1 Input Clock Prescaler

Select Bit Prescaler


T1CKPS1 T1CKPS0 Value

1 1 1:8

1 0 1:4

0 1 1:2

0 0 1:1

Timer 1 can operate in one of the two modes

 As a timer (TMR1CS = 0). In the timer mode, Timer 1 increments in


every instruction cycle. The timer 1 clock source is . 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 the counter mode, external clock input


from the pin RCO/T1CKI is selected.

Reading and writing Timer 1

Reading TMR1H and TMR1L from Timer 1, when it is running from an


external clock source, have to be done with care. Reading TMR1H or TMR1L
for independent 8 - bit values does not pose any problem. When the 16-bit
value of the Timer is required, the high byte (TMR1H) is read first followed
by the low byte (THR1lL). It should be ensured that TMR1L does not
overflow (that is goes from FFH to 00H) since THR1H was read. This
condition is verified by reading TMR1H once again and comparing with
previous value of TMR1H.

Calculating Count, Fout, and Timer1 values

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

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.
(65 536 - TMR1)- The number of times in the timer will count based on the
register TMR0.

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


follow:

Timer 1/CCP Programmable Period Scaler

Timer 1 and one of the CCP module can be used as a scaler. This takes
advantage of thr CCP module’s tiggers special events mode. When the
comparetakes place between TMR1 and the compare register (CCPR1 or
CCPR2). TMR1 is reset to zero giving a period of one greater than the value
loaded into CCPR1 (or CCPR2) the register ans circuit are shown in the
figure 6.11 using CCP1 module
Example:

Reading 16 bit of free running timer 1

movf TMR1H; reaf high byte

movwf TMPH ;store in TMPH

movf TMRL; readlow byte

movwf TMPL; store in TMPL

movf TMR1H,W; read hye byte in W

subwf TMPH ,W; subract1st read with 2nd read

btfsc STATUS,Z; and check for equality

goto next;

: if high bytes differ, then there is an overflow

:read the high byte again followed by the low byte

movf TMR1H; reaf high byte

movwf TMPH
movf TMR1L,W; read low byte in W

movwf TMPL

net:nop

Timer 1 External Event Counter

Timer 1 like timer0, can be used to count external events. When used with
one of the CCP modules, it can generate a CCP interrupt after every Nth
input edge , for any integer value of N upto 65536 with timer1 prescaler,
this can be extended to every multiple of 8 up to 524288.

This basic counter is show in the figure 6.12 this is all that is need to count
N events with T1CON setr to H’02 the prescaler is bypassed and the input
from the pin0 of PORTC, the external clock input to timer1 (T1CK1) is
blocked by TMR1ON = 0 to count N input rising edges TMR1 is preset to
65536-N, the TMR1IF flag in the P1R! register is cleared , and the TMR1IE
interrupt enable bit in the PIE1 register is set . finally counting is begun by
setting TMR1ON bit in the T1CON register ,after N raising edges on the
input pin RC0/T1CK1, Timer 1 will generate an interrupt, permitting the
desired action to be taken at that time.

The synchronizer in the figure 6.12 synchronizes the input to the internal
clock. It is an optional feature, control by the NOT_T1SYNC (bit 2 ) of the
T1CON register. Synchronizing the external input clock. It is an optional
feature, controlled by thr NOT_T1SYNC bit of T1CON register.
Synchronizing the external input to the internal clock permits TMR1 to be
read from and write to. Even as the counter is counting , synchronization is
also vital to proper operation when timer 1 is used with one of the CCP
modules while counting external events. The state of the NOT_T1SYNC bit is
ignored, and the synchronizer bypassed, when TMR1CS=0 select the
internal clock OSC/4
Timer1 and Sleep Mode:

One option that PIC chips make available to uses is the ability to stop the
internal clock(OSC/4) reducing power consumption significantly, and yet
have an accurate internal time base. Timer1 includes the pins and the
oscillator circuit to allow 32768 Hz crystal to save as its external clock
source. Since the synchronizer of figure6.12 will not produce output pluses
with the OSC/$ internal clock stopped, the synchronizer must be bypassed
TMR1 will overflow at 2-secound , 4-secound, 8-secpund, or 16-secound
intervals, depending on which prescaler value is used. The circuit is show in
the figure6.13

Each time tahat a TMR1 overflow occurs, the CPU initiates the startup of
the internal clock which may take as long as 1000 internal clock cycle
before the next instruction executed. If GIE bit had been cleared before the
Sleep instruction had been executed, then about a millisecound after TMR1
overflows, the CPU will countine execution with the code that follows the
Sleep instruction . if GIE=1 then about a millisecound after TMR1
overflows, the CPU will execute the one instruction that follows the sleep
instruction and then vector to the interrupt service routine at address
H’004’
Timer 2 Overview

 Timer 2 is an 8 - bit timer with a pre-scaler and a post-scaler. It can


be used as the PWM time base for PWM mode of capture compare
PWM (CCP) modules. The TMR2 register is readable and writable and
is cleared on device reset.

 The input clock ( ) has a pre-scaler option of 1:1, 1:4 or 1:16


which is selected by bit 0 and bit 1 of T2CON register respectively.

 The Timer 2 module has an 8bit period register (PR2). Timer-2


increments from 00H until it is equal to PR2 and then resets to 00H
on the next clock cycle. PR2 is a readable and writable register. PR2 is
initailised to FFH on reset.

 The output of TMR2 goes through a 4bit post-scaler (1:1, 1:2, to 1:16)
to generate a TMR2 interrupt by setting TMR2IF.

Timer Clock Source

The Timer2 module has one source of input clock, the device clock
(FOSC/4). A prescale option of 1:1, 1:4 or 1:16 is software selected by
control bits T2CKPS1:T2CKPS0 (T2CON<1:0>).

Timer (TMR2) and Period (PR2) Registers

The TMR2 register is readable and writable, and is cleared on all device
resets. Timer2 increments from 00h until it matches PR2 and then resets
to 00h on the next increment cycle. PR2 is a readable and writable
register. TMR2 is cleared when a WDT, POR, MCLR, or a BOR reset
occurs, while the PR2 register is set.

Timer2 can be shut off (disabled from incrementing) by clearing the


TMR2ON control bit(T2CON<2>). This minimizes the power consumption
of the module.
TMR2 Match Output

The match output of TMR2 goes to two sources:

1. Timer2 Postscaler

2. SSP Clock Input (Synchronous Serial Port module)

There are four bits which select the postscaler. This allows the postscaler
a 1:1 to 1:16 scaling(inclusive). After the postscaler overflows, the TMR2
interrupt flag bit (TMR2IF) is set to indicate the Timer2 overflow. This is
useful in reducing the software overhead of the Timer2 interrupt service
routine, since it will only execute once every postscaler # of matches.

The match output of TMR2 is also routed to the Synchronous Serial Port
module, which may software select this as the clock source for the shift
clock

Clearing the Timer2 Prescaler and Postscaler

The prescaler and postscaler counters are cleared when any of the
following occurs:

• a write to the TMR2 register

• a write to the T2CON register

• any device reset (Power-on Reset, MCLR reset, Watchdog Timer Reset,
Brown-out Reset,or Parity Error Reset)

Sleep Operation

During sleep, TMR2 will not increment. The prescaler will retain the last
prescale count, ready for operation to resume after the device wakes from
sleep.
T2CON: TIMER2 CONTROL REGISTER (ADDRESS 12h)

Capture / Compare /PWM (CCP) Modules:

PIC16C74A has two CCP Modules. Each CCP module contains a 16 bit
register (two 8-bit registers) and can operate in one of the three modes, viz.,
16-bit capture, 16-bit compare, or up to 10-bit Pulse Width Modulation
(PWM). The details of the two modules (CCP1 and CCp2) are given as
follows.

CCP1 Module:

CCP1 Module consists of two 8-bit registers, viz., CCPR1L (low byte) and
CCPR1H (high byte). The CCP1CON register controls the operation of CCP1
Module.

CCP2 Module:

CCP2 Module consists of two 8 bit registers, viz., CCPR2L (Low byte) and
CCPR2H (high byte). The CCP1CON register controls the operation of CCP2
Module.

Both CCP1 and CCP2 modules are identical in operation with the exception
of the operation of special event trigger.

The following table shows the timer resources for the CCP Mode.
CCP1CON Register (Address 17H )

CCP2CON Register is exactly similar to CCP1CON register. CCP2CON


Register address is 1DH. CCP1CON controls CCP module1 where as
CCP2CON controls CCP Module2.

Bit 5-4:

CCP1X CCP1Y: PWM least significant bits. These bits are of no use in
Capture mode. In PWM Mode, these bits are the two Lsbs of the PWM duty
cycle. The eight Msbs are found in CCPR1L. Thus the PWM mode operates
in 10-bit mode.

Bit 3-0:

CCP1M3:CCP1MO (CCP1 Mode select bits)

0000=Capture/Compare/PWM Mode off

0100=Capture mode, every falling edge

0101=Capture mode, every rising edge

0110=Capture mode, every 4 th rising edge

0111=Capture mode, every 16 th rising edge

1000=Compare mode, set output on match (CCP1IF bit is set)

1001=Compare mode, clear output on match (CCP1IF bit is set)

1010=Compare mode, generate software interrupt on match (CCP1IF bit is


set, CCP1 pin unaffected)
1011=Compare mode, trigger special event (CCP1IF bit is set;CCP1 resets
Tmr1; CCP2 resets TMR1 and starts A/D conversion if A/D module is
Enabled)

11XX=PWM mode.

Capture Mode (CCP1):

Capture Mode captures the 16-bit value of TMR1 into CCPR1H:CCPR1L


register pair in response to an event occurring on RC2/CCP1 pin. Capture
Mode for CCP2 is exactly similar to that of CCP1.

An event on RC2/CCP1 pin is defined as follows:

 Every falling edge

 Every rising edge.

 Every 4 th rising edge.

 Every 16 th rising edge.

As mentioned earlier, this event is decided by bit 3-0 of CCP1CON register.

The combination of Timer1 and either the CCP1 or the CCP2 module
permits a PIC chip tot be used to determine the time of occurance of an
input edge. Timer1 can be used with its prescaler to let its 16-bit count
range measure longer intervals directly. How ever the finiest resolution in
the measurement result will occure if the prescaler is bypassed. Thus with
OSC=4MHz and bypassing the prescaler, the time of occurance of an input
edge will be ascertained to within 1µs

Figure 6.9 shows the registers and circuity involved with the use of CCP1
module. The time between two input edges is determine by making two
captures and subtracting the one time from the other.
Schematic diagram for capture mode of operation
Required condition for capture mode:

1. RC2/CCP1 pin should be configured as an input by setting TRISC


(bit 2).

2. Timer 1 should be operated from the internal clock (fosc/4), i.e.,


timer mode or in synchronized counter mode.

Compare Mode (CCP1)

Compare mode for CCP2 is similar to that of CCP1, except that in special
event trigger mode, CCP1 resets TMR1 only, whereas CCP2 resets TMR1
and starts A/D conversion if A/D module is enabled.

In compare mode, the 16-bit CCPR1 register value is compared against


TMR1 register pair (TMR1H and TMR1L) value. When a match occurs, the
RC2/CCP1 pin is driven high or driven low or remains unchanged as
decided by CCP1CON<3:0> bits.

Required conditions for compare mode

1. RC2/CCP1 pin must be configured as an output by clearing


TRISC<2> bit.

2. Timer-1 should be operated in timer mode (i.e., internal clock


source of fosc/4) or in synchronized counter mode.

Timer1 is 16 bit counter that together with a CCP module can derive a pin
high or low at a precisely controlled time,independent of what the CPU is
doing at that time. Of the seven PIC family members considered all have two
CCP modules except PIC16C62A, PIC16C64A, and the PIC16C72, ehich
has only one. Consequently, they can all control the RC1/CCP2 pin. These
pin disgnation indicate the alternative role played by these pins as general
purpose I/O pins of PORTC.

While timer1 includes a prescaler to divide the internal clock by 1,2,4,or 8,


the choice of divide by one gives the finest resolution in setting the time of
an output edge. That is with OSC = 4 MHz, the timing of the edges of a pulse
can be controlled with a resolution of 1µs. the initialization for the CCP1
compare mode is show in the figure 6.7

For the PIC chips having two CCP modules, if both modules are being used
for either a compare funcation or for a capture funcation, they will share
TMR1. In this TMR1 should never be changed by writing to it. How ever if
TMR1 is being in one role only, its use is simplified by being able to stop its
clocking by clearing the TMR1ON bit in the T1CON register, clearing TMR1
setting up CCPR1, and then starting the clocking of TMR1 again

In software interrupt mode, CCP1IF bit is set but CCP1 pin in unaffected.
As shown in the figure, in special event trigger mode, both CCP1 and CCP2
initiates an A/D conversion.PWM mode (CCP1)Both CCP1 and CCP2 have
similar operation in PWM mode. Here we will discuss PWM with respect to
CCP1.
Pulse width Modulation:
In PWM mode, the CCP1 pin produces up to a 10-bit resolution Pulse
Width Modulation (PWM) output. RC2/CCP1 pin should be configured in
the output mode by clearing TRISC<2> bit.

A pulse width modulation(PWM) output from a PIC chip is show in the


figure6.14a. for many application, the shorter the period the better.for
example in figure 6.15a, is a variable duty cycle of PWM output to generate
a dc voltage between oV and 5V by using low pass filter to form the
waveform average value. The shorter the PWM period, the faster the average
value can change. If the changes in the PWM signal are characterized by a
maximum frequency fmaxsignal as show in the figure 6.14b

Fmaxsignal <<Fcutofffilter << FPWM


That is the filter’s cutoff frequency needs to be below the frequency of yhe
PWM waveform, Fpwm to remove its fundamental component and its
harmonics at 3 Fpwm, 5 Fpwm, 7 Fpwm etc. And to leave just the relatively
slowly varying DC component. The shorter the period of the PWM waveform
the easier it is to accommodate the signal frequencies with a filter that
passes them unharmedand that essentially removes the effect of pulse width
modulation.

The heart of the PIC’s PWM circuit is a 10bit counter formed from timer2’s
8-bit TMR2 counter for its upper bits and whatever 2 bit counter drives it.
As show in the figure 6.16a, these latter 2 bits depend on the prescaler
setting. If the prescaler is bypassed(ie set to divide by 1) as in the figure
6.16b, then the PWM circuity actually reaches into the 2 bit Q counter
which divides the crystal clock frequency by four to obtain the internal clock
frequency. This is the choice that leads to shortest period of the PWM
waveform.

The period of the waveform is controlled by the circuit of figure 6.17. this
figure shows that the period is controlled by two things: (i) the value
initialized for the Timer2 prescaler and (ii) the value initialized by PR2.
In addition to controlling the PWM frequency the value loaded to PR2
controls the duty cycle resoluation. Thus the circuity in figure 6.17a turns
on the PWM output , other circuitry will turn it off at any desired count of
the 10-bit counter in this figure. Consequently ,if PR2 is initialized to 63, the
full 10-bit counter will count with a scale of 64*4=256, or 8 bit resoluation

For OSC=4MHz, some choices of duty cycle resoluation and prescaler


divider lead to the PWM frequency value show in the figure 6.18.if Timer2 is
also to control the looptime, then the PWM circuity will have almost full 10
bit resoluation. The divide-by-four prescaler choice sets the PWM frequency
to 1KHz. Actually for OSC=4MHz, the stepup of Timer2 can achive the
same looptime performancewith divided by one prescaler and a divided by
eight postscaler this change quadruples the PWM frequency to 4KHz

The circuitry that controls the ontime of the PWM waveform is contained
entirely in the CCP circuitry. For the RC2/CCP1 output, this CCP1 circuitry
is show in the figure 6.19a. this circuit illustrates how the 10bit value is
formed that turns off the PWM output, thus controlling the duty cycle whose
value is given by figure 6.19b.

The upper 8 bits of the 10bits value arre loaded under program control into
CCPR1L.the PWM circuitry automatically transfers this value to CCPR1H as
TMR2 is reset to start each PWM period. This double buffering of the value
that isactually used in the comparison is designed to help prevent the glitch
that would occure in CCPR1H were changed from H’50’ to H’40’. In this
event, the PWM output would not go low at all until the next period

The lower 2 bits of the 10bit value are loaded under program control into
bits 5 and 4 of CCP1CON. If a 10 bit valueis loaded into a 2 byte RAM
variable PWM (made upof PWMH and PWML) then the code will transfer it
to CCPR1L and CCP1CON appropriately to vary the output over the full
duty cycle range from zero to one.
PWMupdate
Rrf PWMH,F ;rotate bit8
Rrf PWML,F ;into PWML[7]
Rrf PWMH,F ;rotate bit 0 into PWML[7]
Rrf PWML,F ;and bit 9 into PWML[7]
Rrf PWMH,F ;and bits 1,0 into PWMH[7:6]
;upper 8 bits are now in PWML
;lower 2 bits are in PWML[7:6]
Rrf PWMH,F ;move bits 1,0 to align with CCP1CON
Rrf PWMH,W ;and move to W
Xorwf CCP1CON,W ;toggle if CCP1X;CCP1Y differ
Andlw B’00110000’ ;force other bits to zero
Xorwf CCP1CON,F ;chane bits that differ
Movf PWML,W ;move upper 8 bit
Movwf CCPR1l
Return ;fourteen cycles
The schematic block diagram of CCP1 module in PWM mode is shown in the
figure.

It can be noted that PR2 (Period Register, 8 bit) decides the PWM period
where CCPR1L (8-bits) and CCP1CON <5:4> (2-bits) decide the PWM duty
cycle. When TMR2 equals PR2, the SR latch is set and RC2/CCP1 pin is
pulled high. In the same time, TMR2 is cleared and the duty cycle value
available in CCPR1L is latched to CCPR1H. CCPR1H, CCP1CON <5:4>
decide the duty cycle and when this 10-bit equals the TMR2+2 prescaler or
Q-bits, the SR latch is set and RC2/CCP1 pin is driven low.
A PWM output as shown has a time period. The time for which the output
stays high is called duty cycle.

PWM Period

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

PWM period = [( PR 2) + 1] × 4 × T osc × (TMR2 prescale value)


PWM frequency = 1/ PWM period

When TMR2 is equal to PR2, the following events occur on the next
increment cycle.

 TMR2 is cleared

 the CCP1 pin is set (if PWM duty cycle is 0

 The PWM duty cycle is latched from CCPR1L into CCPR1H

 PWM duty cycle

The PWM duty cycle is specified by writing to the CCPR1L register and to
CCP1CON < 5 : 4 >bits. Up to 10-bit resolution is available where CCPR1L
contains the eight MSBs and CCP1CON < 5 : 4 > contains the two LSB's.
The 10-bit value is represented by CCPR1L : CCP1CON < 5 : 4 >.

The PWM duty cycle is given by


PWM duty cycle = (CCPR1L : CCP1CON < 5 : 4 > ). T osc . (TMR2 prescale
value) To understand the 10-bit counter configuration from Timer-2, let us
first see the counting mechanism of Timer-2, as shown in Fig
Although CCPR1L and CCP1CON < 5 : 4 > can be written to at anytime, the
duty cycle value is not latched into CCPR1H until a match between PR2 and
TMR2 occurs. In PWM mode, CCPR1H is a read-only register.

The CCPR1H register and a 2-bit internal latch are used to double buffer the
PWM duty cycle. This double buffering is essential for glitch less PWM
operation. When the CCPR1H and 2-bit latch match TMR2 concatenated
with an internal 2-bit Q clock or 2-bits of prescaler, the CCP1 pin is cleared.
Maximum PWM resolution (bits) for a given PWM frequency can be
calculated as

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.

Application of PWM to drive a Load:

For other application such filtering is unnecessary figure 6.15b show a


driver circuit that can be used to control the temperature of aheater winding
or the intensity of a light source. The tiny power MOSFET is an almost ideal
driver. Its high impedance input is easy to derive and has an unusually low
input threshold of 3V. that is for an input voltage about 4V. the drain-
source equivqlent circuit is a very low resistance. For an input voltage 0V,
the drain source resistance is in the meghaohms.

Front-Panel I/O :

Design of instruments and other devices that requires intractions 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 stepup parameters. For example, so
the user can see successive digit entires combine and form the desired
amplitude. An RPG offers the desirable feature of being able to increment or
decriment the value of sttepup parameter being displayed on the LCD

Soft Keys:

A multiple line LCD display presents the opportunity, show in the figure 8.1
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 circuit in the figure 8.2 illustrate how the four soft keys figure 8.1 can
be treated in the same manner as the 12keys of keypad. Infact , keyswitchs
are generally grouped into array such as this whether or not they are
physically grouped together in a keypad . figure 8.2 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.
State machines and keyswitches:

Keyswitches are not changed very fast, they can be checked once each time
around the mainline loop in a keySwitch subroutine. Recall that a looptime
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
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

A flow chart of the keyswitch subroutine algorithm is show in the figure 8.3
each time keyswitch is called, if no key has been pressed during the last
several calls, then KEYSTATE will equal zero. The job of the keyswitch
subroutine in this case is to determine whether any key us newly pressed

The keyswitch algorithm of figure 8.3 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 in the


figure 8.4. it 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.
Ifa 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 in figure 8.2 are there to product 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 relese key
;;;;;;;;;;;;;ScanKeys subroutine;;;;;;;;;;;;;;;;;;
ScanKeys
clrf KEYCODE ;Startby checking the “0” key
ScanKeys_1
call ScanKeys_Table ;get next table entry
movwf TEMP
bcf PORTD,7 ;PD7<- bit 0 of table entry
btfsc TEMP,0
bsf PORTD,7
movwf PORTB ;PB3,2,1 fromtable entry
xorfwf PORTB,W ;compare upper 4 bitsor PORTB with table entry
andlw B’11110000’ ;z=1 if a match
btfsc STATUS,Z
goto ScanKeys_done
incf KEYCODE,F ;try next key
btfsc KEYCODE,4 ;stop with Z=0 when KEYCODE =B’XXX1XXXX’
goto ScanKeys_1
ScanKeys_done
Return
;;;;;;;; ScanKeys_Table subroutine;;;;;;;;;;;;;;;;;;;
ScanKeys_Table
Movf KEYCODE,W
Addwf PCL,F ;Change PC with PCLATH=H’00’
retlw B’11101011’ ; Test “0” Key
retlw B’01110111’ ; Test “1” Key
retlw B’01111011’ ; Test “2” Key
retlw B’01111101’ ; Test “3” Key
retlw B’10110111’ ; Test “4” Key
retlw B’10111011’ ; Test “5” Key
retlw B’10111101’ ; Test “6” Key
retlw B’11010111’ ; Test “7” Key
retlw B’11011011’ ; Test “8” Key
retlw B’11011101’ ; Test “9” Key
retlw B’11100111’ ; Test “*” Key
retlw B’11101101’ ; Test “#” Key
retlw B’01111110’ ; Test SK1
retlw B’10111110’ ; Test SK2
retlw B’11011110’ ; Test SK3
retlw B’11101110’ ; Test SK4

Figuer8.4 ScanKey subroutine and its table subroutine

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 detented position per
revoluation 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 decreasethe value of
parameter. Detents support this funcation 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 twoRPG output must be treated differently from keyswitches since trhe
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 intrreput input. In the case of grayhilll RPG,
action is needed whenever either output change, not just when one of the
output riseing 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 inceremented or
decremented if the input have change
Display of variable string:

When entering setup paramenter 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 illustrate in fig 8.7. assume that a display string has
the formate as show in figure 8.7c:

1. Cursor position code (Figuer 7.8)


2. ASCII string of characters to be displayed
3. Endof string designator,H’00’

Given string having this formate, 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 character evere to be send 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 illustrate in the figure 8.7a and 8.7b. the MPASM assembler
permits code writers to creat error message to warn of error producing
condition.

VSTRINGlenght equ 12 ; maximum number of characters in VSTRING


Fig 8.7 (a) Equates section of code
cblock Bank0RAM
.
.
.
VSTRING: VSTRINGlength
Marker
endc
if marker>H'80'
error “ RAM use exceeds bank 0”
endif
Fig 8.7 (b) Assigning a variable string to RAM
Address RAM Content comments
VSTRING H'E4' Cursor – positioning code
VSTRING+1 H'33'
VSTRING+2 H'31'
VSTRING+3 H'32' four digit number 3126
VSTRING+4 H'36'
VSTRING+5 H'00' End of string designator

Fig 8.7 (c)Display string example

Figuer 7.9 : Display of Character and its ASCII Code


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

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 remainderthat 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 intrest.
The offset in the code is loaded to W before DisplayC subroutine is called .
ehen 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

You might also like