Unit 2
Unit 2
Introduction:
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.
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.
Interrupts in PIC16C6X:
• USART Interrupts
• Receive Interrupt
• Transmit Interrupt
• LCD 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:
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
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)
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.
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.
Interrupt Constrain:
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
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
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
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
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
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
TIMER MODULES:
Timer 0
Timer1
Timer2
Timer 0:
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 2
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.
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
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.
1 1 1:8
1 0 1:4
0 1 1:2
0 0 1:1
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:
goto next;
movwf TMPH
movf TMR1L,W; read low byte in W
movwf TMPL
net:nop
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
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.
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>).
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.
1. Timer2 Postscaler
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
The prescaler and postscaler counters are cleared when any of the
following occurs:
• 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)
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 )
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:
11XX=PWM mode.
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:
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.
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.
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.
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
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:
When TMR2 is equal to PR2, the following events occur on the next
increment cycle.
TMR2 is cleared
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 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
Front-Panel I/O :
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
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
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
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
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
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
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