Microchip PIC24FJ64GA406 Handleiding


Lees hieronder de 📖 handleiding in het Nederlandse voor Microchip PIC24FJ64GA406 (137 pagina's) in de categorie Niet gecategoriseerd. Deze handleiding was nuttig voor 12 personen en werd door 2 gebruikers gemiddeld met 4.5 sterren beoordeeld

Pagina 1/137
© 2009 Microchip Technology Inc. DS01146B
Compiled Tips ‘N Tricks Guide
DS01146B-page ii © 2009 Microchip Technology Inc.
Information contained in this publication regarding device
applications and the like is provided only for your convenience
and may be superseded by updates. It is your responsibility to
ensure that your application meets with your specifications.
MICROCHIP MAKES NO REPRESENTATIONS OR
WARRANTIES OF ANY KIND WHETHER EXPRESS OR
IMPLIED, WRITTEN OR ORAL, STATUTORY OR
OTHERWISE, RELATED TO THE INFORMATION,
INCLUDING BUT NOT LIMITED TO ITS CONDITION,
QUALITY, PERFORMANCE, MERCHANTABILITY OR
FITNESS FOR PURPOSE. Microchip disclaims all liability
arising from this information and its use. Use of Microchip
devices in life support and/or safety applications is entirely at
the buyer’s risk, and the buyer agrees to defend, indemnify and
hold harmless Microchip from any and all damages, claims,
suits, or expenses resulting from such use. No licenses are
conveyed, implicitly or otherwise, under any Microchip
intellectual property rights.
Trademarks
The Microchip name and logo, the Microchip logo, Accuron,
dsPIC, KEE EELOQ, K LOQ logo, MPLAB, PIC, PICmicro,
PICSTART, rfPIC, SmartShunt and UNI/O are registered
trademarks of Microchip Technology Incorporated in the
U.S.A. and other countries.
FilterLab, Hampshire, Linear Active Thermistor, MXDEV,
MXLAB, SEEVAL, SmartSensor and The Embedded Control
Solutions Company are registered trademarks of Microchip
Technology Incorporated in the U.S.A.
Analog-for-the-Digital Age, Application Maestro, CodeGuard,
dsPICDEM, dsPICDEM.net, dsPICworks, dsSPEAK, ECAN,
ECONOMONITOR, FanSense, In-Circuit Serial
Programming, ICSP, ICEPIC, Mindi, MiWi, MPASM, MPLAB
Certified logo, MPLIB, MPLINK, mTouch, nanoWatt XLP,
PICkit, PICDEM, PICDEM.net, PICtail, PIC32 logo, PowerCal,
PowerInfo, PowerMate, PowerTool, REAL ICE, rfLAB, Select
Mode, Total Endurance, TSHARC, WiperLock and ZENA are
trademarks of Microchip Technology Incorporated in the
U.S.A. and other countries.
SQTP is a service mark of Microchip Technology Incorporated
in the U.S.A.
All other trademarks mentioned herein are property of their
respective companies.
© 2009, Microchip Technology Incorporated, Printed in the
U.S.A., All Rights Reserved.
Printed on recycled paper.
Note the following details of the code protection feature on Microchip devices:
Microchip products meet the specification contained in their particular Microchip Data Sheet.
Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the
intended manner and under normal conditions.
There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our
knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data
Sheets. Most likely, the person doing so is engaged in theft of intellectual property.
Microchip is willing to work with the customer who is concerned about the integrity of their code.
Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not
mean that we are guaranteeing the product as “unbreakable.”
Code protection is constantly evolving. We at Microchip are co ng the code protection features ofmmitted to continuously improvi our
products. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such acts
allow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.
Microchip received ISO/TS-16949:2002 certification for its worldwide
headquarters, design and wafer fabrication facilities in Chandler and
Tempe, Arizona; Gresham, Oregon and design centers in California
and India. The Company’s quality system processes and procedures
are for its PIC® MCUs and dsPIC® DSCs, KEELOQ ®
code hopping
devices, Serial EEPROMs, microperipherals, nonvolatile memory and
analog products. In addition, Microchip’s quality system for the design
and manufacture of development systems is ISO 9001:2000 certified.
© 2009 Microchip Technology Inc. Page i-DS01146B
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
Tips ‘n Tricks
TABLE OF CONTENTS
8-pin Flash PIC® Microcontrollers
Tips ‘n Tricks
TIPS ‘N TRICKS WITH HARDWARE
TIP #1: Dual Speed RC Oscillator .......................... 1-2
TIP #2: Input/Output Multiplexing............................ 1-2
TIP #3: Read Three States From One Pin .............. 1-3
TIP #4: Reading DIP Switches ................................ 1-3
TIP #5: Scanning Many Keys With One Input......... 1-4
TIP #6: Scanning Many Keys and Wake-up
From Sleep ................................................. 1-4
TIP #7: 8x8 Keyboard with 1 Input .......................... 1-5
TIP #8: One Pin Power/Data................................... 1-5
TIP #9: Decode Keys and ID Settings .................... 1-6
TIP #10: Generating High Voltages .......................... 1-6
TIP #11: V Self Starting Circuit ............................. 1-7dd
TIP #12: Using PIC
®
MCU A/D For Smart
Current Limiter............................................ 1-7
TIP #13: Reading A Sensor With Higher Accuracy ... 1-8
TIP #13.1: Reading A Sensor With Higher
Accuracy – RC Timing Method ................... 1-8
TIP #13.2: Reading A Sensor With Higher
Accuracy – Charge Balancing Method .......1-10
TIP #13.3: Reading A Sensor With Higher
AccuracyA/D Method ..............................1-11
TIP #14: Delta Sigma Converter ...............................1-11
TIPS ‘N TRICKS WITH SOFTWARE
TIP #15: Delay Techniques .......................................1-12
TIP #16: Optimizing Destinations..............................1-13
TIP #17: Conditional Bit Set/Clear ............................1-13
TIP #18: Swap File Register with W .........................1-14
TIP #19: Bit Shifting Using Carry Bit .........................1-14
PIC® Microcontroller Low Power
Tips ‘n Tricks
GENERAL LOW POWER TIPS ‘N TRICKS
TIP #1 Switching Off External Circuits/
Duty Cycle .................................................. 2-2
TIP #2 Power Budgeting ........................................ 2-3
TIP #3 Conguring Port Pins ................................. 2-4
TIP #4 Use High-Value Pull-Up Resistors .............. 2-4
TIP #5 Reduce Operating Voltage ......................... 2-4
TIP #6 Use an External Source for
CPU Core Voltage ...................................... 2-5
TIP #7 Battery Backup for PIC MCUs ................... 2-6
DYNAMIC OPERATION TIPS ‘N TRICKS
TIP #8 Enhanced PIC16 Mid-Range Core ............. 2-6
TIP #9 Two-Speed Start-Up ................................... 2-7
TIP #10 Clock Switching .......................................... 2-7
TIP #11 Use Internal RC Oscillators ........................ 2-7
TIP #12 Internal Oscillator Calibration ..................... 2-8
TIP #13 Idle and Doze Modes ................................. 2-8
TIP #14 Use and Idle Mode .............................. 2-9NOP
TIP #15 Peripheral Module Disable
(PMD) Bits .................................................. 2-9
STATIC POWER REDUCTION TIPS ‘N TRICKS
TIP #16 Deep Sleep Mode.......................................2-10
TIP #17 Extended WDT and Deep
Sleep WDT .................................................2-10
TIP #18 Low Power Timer1 Oscillator and RTCC ....2-10
TIP #19 Low Power Timer1 Oscillator Layout ..........2-11
TIP #20 Use LVD to Detect Low Battery ..................2-11
TIP #21 Use Peripheral FIFO and DMA...................2-11
TIP #22 Ultra Low-Power
Wake-Up Peripheral ...................................2-12
PIC® Microcontroller CCP and ECCP
Tips ‘n Tricks
CAPTURE TIPS ‘N TRICKS
TIP #1: Measuring the Period of a Square Wave ... 3-3
TIP #2: Measuring the Period of a
Square Wave with Averaging ..................... 3-3
TIP #3: Measuring Pulse Width .............................. 3-4
TIP #4: Measuring Duty Cycle ................................ 3-4
TIP #5: Measuring RPM Using an Encoder ............ 3-5
TIP #6: Measuring the Period of an Analog Signal 3-6 .
COMPARE TIPS ‘N TRICKS
TIP #7: Periodic Interrupts ...................................... 3-8
TIP #8: Modulation Formats.................................... 3-9
TIP #9: Generating the Time Tick for a RTOS ........3-10
TIP #10: 16-Bit Resolution PWM ..............................3-10
TIP #11: Sequential ADC Reader .............................3-11
TIP #12: Repetitive Phase Shifted Sampling ............3-12
PWM TIPS ‘N TRICKS
TIP #13: Deciding on PWM Frequency.....................3-14
TIP #14: Unidirectional Brushed DC
Motor Control Using CCP ...........................3-14
TIP #15: Bidirectional Brushed DC
Motor Control Using ECCP ........................3-15
TIP #16: Generating an Analog Output .....................3-16
TIP #17: Boost Power Supply ...................................3-17
TIP #18: Varying LED Intensity .................................3-18
TIP #19: Generating X-10 Carrier Frequency ...........3-18
COMBINATION CAPTURE AND COMPARE TIPS
TIP #20: RS-232 Auto-baud ......................................3-19
TIP #21: Dual-Slope Analog-to-Digital Converter .....3-21
© 2009 Microchip Technology Inc.Page ii-DS01146B
Tips ‘n Tricks Table of Contents
PIC® Microcontroller Comparator
Tips ‘n Tricks
TIP #1: Low Battery Detection ................................ 4-2
TIP #2: Faster Code for Detecting Change............. 4-3
TIP #3: Hysteresis................................................... 4-4
TIP #4: Pulse Width Measurement ......................... 4-5
TIP #5: Window Comparison .................................. 4-6
TIP #6: Data Slicer .................................................. 4-7
TIP #7: One-Shot .................................................... 4-8
TIP #8: Multi-Vibrator (Square Wave Output) ......... 4-9
TIP #9: Multi-Vibrator (Ramp Wave Output) ...........4-10
TIP #10: Capacitive Voltage Doubler ........................4-11
TIP #11: PWM Generator .........................................4-12
TIP #12: Making an Op Amp Out of a Comparator ...4-13
TIP #13: PWM High-Current Driver ..........................4-14
TIP #14: Delta-Sigma ADC .......................................4-15
TIP #15: Level Shifter ...............................................4-16
TIP #16: Logic: Inverter.............................................4-16
TIP #17: Logic: AND/NAND Gate .............................4-17
TIP #18: Logic: OR/NOR Gate..................................4-18
TIP #19: Logic: XOR/XNOR Gate .............................4-19
TIP #20: Logic: Set/Reset Flip Flop ..........................4-20
PIC® Microcontroller DC Motor Control
Tips ‘n Tricks
TIP #1: Brushed DC Motor Drive Circuits ............... 5-2
TIP #2: Brushless DC Motor Drive Circuits ............. 5-3
TIP #3: Stepper Motor Drive Circuits ...................... 5-4
TIP #4: Drive Software ............................................ 5-6
TIP #5: Writing a PWM Value to the CCP
Registers with a Mid-Range PIC
®
MCU ..... 5-7
TIP #6: Current Sensing ......................................... 5-8
TIP #7: Position/Speed Sensing ............................. 5-9
Application Note References .........................................5-11
Motor Control Development Tools .................................5-11
LCD PIC® Microcontroller Tips ‘n Tricks
TIP #1: Typical Ordering Considerations and
Procedures for Custom Liquid Displays ..... 6-2
TIP #2: LCD PIC
®
MCU Segment/Pixel Table ......... 6-2
TIP #3: Resistor Ladder for Low Current ................ 6-3
TIP #4: Contrast Control with a Buck Regulator ..... 6-5
TIP #5: Contrast Control Using a Boost
Regulator .................................................... 6-5
TIP #6: Software Controlled Contrast with
PWM for LCD Contrast Control .................. 6-6
TIP #7: Driving Common Backlights ....................... 6-7
TIP #8: In-Circuit Debug (ICD) ................................ 6-8
TIP #9: LCD in Sleep Mode .................................... 6-8
TIP #10: How to Update LCD Data
Through Firmware ...................................... 6-9
TIP #11: Blinking LCD............................................... 6-9
TIP #12: 4 x 4 Keypad Interface that Conserves
Pins for LCD Segment Drivers ...................6-10
Application Note References .........................................6-11
Intelligent Power Supply Design
Tips ‘n Tricks
TIP #1: Soft-Start Using a PIC10F200 .................... 7-2
TIP #2: A Start-Up Sequencer ................................ 7-3
TIP #3: A Tracking and Proportional
Soft-Start of Two Power Supplies ............... 7-4
TIP #4: Creating a Dithered PWM Clock ................ 7-5
TIP #5: Using a PIC
®
Microcontroller as a Clock
Source for a SMPS PWM Generator.......... 7-6
TIP #6: Current Limiting Using the MCP1630 ......... 7-7
TIP #7: Using a PIC
®
Microcontroller for
Power Factor Correction ............................ 7-8
TIP #8: Transformerless Power Supplies ............... 7-9
TIP #9: An IR Remote Control Actuated AC
Switch for Linear Power Supply Designs ...7-10
TIP #10: Driving High Side FETs ..............................7-11
TIP #11: Generating a Reference Voltage with a
PWM Output ...............................................7-12
TIP #12: Using Auto-Shutdown CCP ........................7-13
TIP #13: Generating a Two-Phase Control Signal ....7-14
TIP #14: Brushless DC Fan Speed Control ..............7-15
TIP #15: High Current Delta-Sigma Based Current
Measurement Using a Slotted Ferrite
and Hall Effect Device ................................7-16
TIP #16: Implementing a PID Feedback Control
in a PIC12F683-Based SMPS Design........7-17
TIP #17: An Error Detection and Restart Controller..7-18
TIP #18: Data-Indexed Software State Machine.......7-19
TIP #19: Execution Indexed Software
State Machine ............................................7-20
TIP #20: Compensating Sensors Digitally ................7-21
TIP #21: Using Output Voltage Monitoring to
Create a Self-Calibration Function .............7-22
3V Tips ‘n Tricks
TIP #1: Powering 3.3V Systems From 5V
Using an LDO Regulator ............................ 8-3
TIP #2: Low-Cost Alternative Power System
Using a Zener Diode .................................. 8-4
TIP #3: Lower Cost Alternative Power System
Using 3 Rectier Diodes ............................. 8-4
TIP #4: Powering 3.3V Systems From 5V
Using Switching Regulators ....................... 8-5
TIP #5: 3.3V → 5V Direct Connect ......................... 8-6
TIP #6: 3.3V → 5V Using a MOSFET Translator .... 8-6
TIP #7: 3.3V → 5V Using A Diode Offset ................ 8-7
TIP #8: 3.3V → 5V Using A Voltage Comparator .... 8-8
TIP #9: 5V → 3.3V Direct Connect ......................... 8-9
TIP #10: 5V → 3.3V With Diode Clamp .................... 8-9
TIP #11: 5V → 3.3V Active Clamp ............................8-10
TIP #12: 5V → 3.3V Resistor Divider........................8-10
TIP #13: 3.3V → 5V Level Translators......................8-12
TIP #14: 3.3V → 5V Analog Gain Block....................8-13
TIP #15: 3.3V → 5V Analog Offset Block ..................8-13
TIP #16: 5V → 3.3V Active Analog Attenuator ..........8-14
TIP #17: 5V → 3V Analog Limiter .............................8-15
TIP #18: Driving Bipolar Transistors .........................8-16
TIP #19: Driving N-Channel MOSFET Transistors ...8-18
© 2009 Microchip Technology Inc. DS01146B-Page 1-1
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
CHAPTER 1
8-Pin Flash PIC® Microcontrollers
Tips ‘n Tricks
Table Of Contents
TIPS ‘N TRICKS WITH HARDWARE
TIP #1: Dual Speed RC Oscillator ................ 1-2
TIP #2: Input/Output Multiplexing .................. 1-2
TIP #3: Read Three States From One Pin .... 1-3
TIP #4: Reading DIP Switches ...................... 1-3
TIP #5: Scanning Many Keys With
One Input .......................................... 1-4
TIP #6: Scanning Many Keys and Wake-up
From Sleep ....................................... 1-4
TIP #7: 8x8 Keyboard with 1 Input ................ 1-5
TIP #8: One Pin Power/Data ......................... 1-5
TIP #9: Decode Keys and ID Settings .......... 1-6
TIP #10: Generating High Voltages ................ 1-6
TIP #11: V Self Starting Circuit.................... 1-7dd
TIP #12: Using PIC® MCU A/D For Smart
Current Limiter .................................. 1-7
TIP #13: Reading A Sensor With Higher
Accuracy ........................................... 1-8
TIP #13.1: Reading A Sensor With Higher
Accuracy – RC Timing Method ......... 1-8
TIP #13.2: Reading A Sensor With Higher
Accuracy – Charge Balancing
Method ............................................. 1-10
TIP #13.3: Reading A Sensor With Higher
Accuracy – A/D Method .................... 1-11
TIP #14: Delta Sigma Converter ..................... 1-11
TIPS ‘N TRICKS WITH SOFTWARE
TIP #15: Delay Techniques ............................. 1-12
TIP #16: Optimizing Destinations .................... 1-13
TIP #17: Conditional Bit Set/Clear .................. 1-13
TIP #18: Swap File Register with W ............... 1-14
TIP #19: Bit Shifting Using Carry Bit ............... 1-14
TIPS ‘N TRICKS INTRODUCTION
Microchip continues to provide innovative
products that are smaller, faster, easier to
use and more reliable. The 8-pin Flash PIC®
microcontrollers (MCU) are used in an wide
range of everyday products, from toothbrushes,
hair dryers and rice cookers to industrial,
automotive and medical products.
The PIC12F629/675 MCUs merge all the
advantages of the PIC MCU architecture and
the exibility of Flash program memory into
an 8-pin package. They provide the features
and intelligence not previously available due
to cost and board space limitations. Features
include a 14-bit instruction set, small footprint
package, a wide operating voltage of 2.0 to
5.5 volts, an internal programmable 4 MHz
oscillator, on-board EEPROM data memory,
on-chip voltage reference and up to 4 channels
of 10-bit A/D. The exibility of Flash and an
excellent development tool suite, including
a low-cost In-Circuit Debugger, In-Circuit
Serial Programming™ and MPLAB® ICE 2000
emulation, make these devices ideal for just
about any embedded control application.
TIPS ‘N TRICKS WITH HARDWARE
The following series of Tips ’n Tricks can be
applied to a variety of applications to help make
the most of the 8-pin dynamics.
© 2009 Microchip Technology Inc.Page 1-2 DS01146B
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIP #1 Dual Speed RC Oscillator
Figure 1-1
PIC12F6XX
OSC1
GP0
+5V
R2
R1
C
1. After reset I/O pin is High-Z
2. Output ‘1’ on I/O pin
3. R1, R2 and C determine OSC frequency
4. Also works with additional capacitors
Frequency of PIC MCU in external RC oscillator
mode depends on resistance and capacitance
on OSC1 pin. Resistance is changed by the
output voltage on GP0. GP0 output ‘1’ puts R2
in parallel with R1 reduces OSC1 resistance
and increases OSC1 frequency. GP0 as
an input increases the OSC1 resistance
by minimizing current ow through R2, and
decreases frequency and power consumption.
Summary:
GP0 = Input: Slow speed for low current
GP0 = Output high: High speed for fast
processing
TIP #2 Input/Output Multiplexing
Individual diodes and some combination of
diodes can be enabled by driving I/Os high and
low or switching to inputs (Z). The number of
diodes (D) that can be controlled depends on
the number of I/Os (GP) used.
The equation is: D = GP x (GP - 1).
Example 2-1: Six LEDs on Three I/O Pins
GPx LEDs
0 1 2
0 0 0
0 1 Z
1 0 Z
Z 0 1
Z 1 0
0 Z 1
1 Z 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
1 2 3 4 5 6
0 0 0 0 0 0
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1
0 0 1 0 1 0
1 0 0 1 0 0
1 0 0 0 1 0
0 1 0 0 0 1
0 1 1 0 0 0
0 0 0 1 0 1
0 0 0 0 0 0
Figure 2-1
PIC12F6XX
1 2 5
4
3
6
GP0
GP1
GP2
© 2009 Microchip Technology Inc. DS01146B-Page 1-3
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIP #3 Read Three States
From One Pin
To check state Z:
• Drive output pin high
• Set to Input
• Read 1
• Drive output pin low
• Set to Input
• Read 0
To check state 0:
• Read 0 on pin
To check state 1:
• Read 1 on pin
State Link 0 Link 1
0 closed open
1 open closed
NC open open
Jumper has three possible states: not
connected, Link 1 and Link 0. The capacitor
will charge and discharge depending on
the I/O output voltage allowing the “not
connected” state. Software should check the
“not connected” state rst by driving I/O high,
reading 1 and driving I/O low and reading 0. The
“Link 1” and “Link 0” states are read directly.
PIC
I/O
5V
0V
Link 0
Link 1
Figure 3-1
TIP #4 Reading DIP Switches
The input of a timer
can be used to test
which switch(s)
is closed. The
input of Timer1 is
held high with a
pull-up resistor.
Sequentially,
each switch I/O is
set to input and
Timer1 is checked
for an increment
indicating the
switch is closed.
Each bit in the DP register represents its
corresponding switch position. By setting
Timer1 to FFFFh and enabling its interrupt, an
increment will cause a rollover and generate
an interrupt. This will simplify the software by
eliminating the bit test on the TMR1L register.
Sequentially set each GPIO to an input and test
for TMR1 increment (or 0 if standard I/O pin is
used).
Figure 4-1
PIC12F6XX
GP0
GP1
GP2
GP3
GP5/T1CKI
10K
V
DD
GP4Data I/O
movlw b'11111111'
movwf TRISIO
movwf DIP
movlw b'00000111'
movwf T1CON
movlw b'11111110'
movwf Mask
clrf GPIO
LOOP
clrf TMR1L
movf Mask,W
movwf TRISIO
btfsc TMR1L,0
andwf DIP,F
bsf STATUS,C
rlf Mask,F
btfsc Mask,4
goto Loop
retlw 0
Example 4-1
© 2009 Microchip Technology Inc.Page 1-4 DS01146B
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIP #5 Scanning Many Keys With
One Input
The time required to charge a capacitor
depends on resistance between V and dd
capacitor. When a button is pressed, V is dd
supplied to a different point in the resistor
ladder. The resistance between V and the dd
capacitor is reduced, which reduces the charge
time of the capacitor. A timer is used with a
comparator or changing digital input to measure
the capacitor charge time. The charge time is
used to determine which button is pressed.
Software sequence:
1. Congure GP2 to output a low voltage to
discharge capacitor through I/O resistor.
2. Congure GP2 as one comparator input and
CVref as the other.
3. Use a timer to measure when the comparator
trips. If the time measured is greater than the
maximum allowed time, then repeat;
otherwise determine which button is pressed.
When a key is pressed, the voltage divider
network changes the RC ramp rate.
Figure 5-1
PIC12F6XX
GP0
GP1
GP2
GP4
GP5
GP3
16
Resistors
220
R
R
R
R
See AN512, “Implementing Ohmmeter/
Temperature Sensor” for code ideas.
TIP #6 Scanning Many Keys and
Wake-up From Sleep
An additional I/O can be added to wake the
part when a button is pressed. Prior to Sleep,
congure GP1 as an input with interrupt-on-
change enabled and GP2 to output high. The
pull-down resistor holds GP1 low until a button
is pressed. GP1 is then pulled high via GP2
and V generating an interrupt. After wake-up, dd
GP2 is congured to output low to discharge
the capacitor through the 220Ω resistor. GP1 is
set to output high and GP2 is set to an input to
measure the capacitor charge time.
• GP1 pin connected to key common
• Enable wake-up on port change
• Set GP1 as input and GP2 high prior to Sleep
• If key is pressed the PIC MCU wakes up, GP2
must be set low to discharge capacitor
• Set GP1 high upon wake-up to scan keystroke
Figure 6-1
VDD
100R
PIC12F6XX
GP0
GP1
GP2
GP4
GP5
GP3
220
R
R
R
R
16
Resistors
© 2009 Microchip Technology Inc. DS01146B-Page 1-5
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIP #7 4x4 Keyboard with 1 Input
By carefully selecting the resistor values,
each button generates a unique voltage. This
voltage is measured by the A/D to determine
which button is pressed. Higher precision
resistors should be used to maximize voltage
uniqueness. The A/D will read near 0 when no
buttons are pressed.
Figure 7-1
V
DD
PIC12F6XX
GP0
TIP #8 One Pin Power/Data
A single I/O can be used for both a single-
direction communication and the power source
for another microcontroller. The I/O line is held
high by the pull-up resistor connected to V . dd
The sender uses a pull-down transistor to pull
the data line low or disables the transistor to
allow the pull-up to raise it to send data to the
receiver. V is supplied to the sender through dd
the data line. The capacitor stabilizes the sender’s
V and a diode prevents the capacitor from dd
discharging through the I/O line while it is low.
Note that the V of the sender is a diode-drop dd
lower than the receiver.
Figure 8-1
V
DD
V
DD
Receiver
GP0 GP0
Sender
V
DD
- 0.7V
© 2009 Microchip Technology Inc.Page 1-6 DS01146B
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIP #9 Decode Keys and ID Settings
Buttons and jumpers can share I/O’s by using
another I/O to select which one is read. Both
buttons and jumpers are tied to a shared
pull-down resistor. Therefore, they will read
as ‘0’ unless a button is pressed or a jumper
is connected. Each input (GP3/2/1/0) shares
a jumper and a button. To read the jumper
settings, set GP4 to output high and each
connected jumper will read as ‘1’ on its assigned
I/O or ‘0’ if it’s not connected. With GP4 output
low, a pressed button will be read as ‘1’ on its
assigned I/O and ‘0’ otherwise.
Figure 9-1
V
DD
GP0
GP1
GP2
GP3
GP4
• When GP4 = 1 and no keys are pressed, read
ID setting
• When GP4 = 0, read the switch buttons
TIP #10 Generating High Voltages
Figure 10-1
PIC12F6XX
w/RC CLKOUT
CPUMP CFILTER
CLKOUT
VOUT DD DIODE max = 2 * V - 2 * V
VDD
Voltages greater than V can be generated dd
using a toggling I/O. PIC MCUs CLKOUT/OSC2
pin toggles at one quarter the frequency of
OSC1 when in external RC oscillator mode.
When OSC2 is low, the V diode is forward dd
biased and conducts current, thereby charging
C . After OSC2 is high, the other diode is pump
forward biased, moving the charge to C . filter
The result is a charge equal to twice the V dd
minus two diode drops. This can be used with a
PWM, a toggling I/O or other toggling pin.
© 2009 Microchip Technology Inc. DS01146B-Page 1-7
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIP #11 V Self Starting Circuitdd
Building on the previous topic, the same charge
pump can be used by the MCU to supply its
own V . Before the switch is pressed, V dd bat
has power and the V points are connected dd
together but unpowered. When the button is
pressed, power is supplied to V and the dd
MCUs CLKOUT (in external RC oscillator mode)
begins toggle. The voltage generated by the
charge pump turns on the FET allowing V dd
to remain powered. To power down the MCU,
execute a Sleep instruction. This allows the
MCU to switch off its power source via software.
Advantages:
• PIC MCU leakage current nearly 0
• Low cost (uses n-channel FET)
• Reliable
• No additional I/O pins required
Figure 11-1
PIC12F6XX
CLKOUT
V
DD
V
DD
V
DD
V
BAT
V
DD
TIP #12 Using PIC® MCU A/D For
Smart Current Limiter
Figure 12-1
W
PIC12F6XX
10K
AN0
R
SENSE
Load or Motor
• Detect current through low side sense resistor
• Optional peak lter capacitor
• Varying levels of overcurrent response can be
realized in software
By adding a resistor (R ) in series with a sense
motor, the A/D can be used to measure in-rush
current, provide current limiting, over-current
recovery or work as a smart circuit breaker. The
10K resistor limits the analog channel current
and does not violate the source impedance limit
of the A/D.
© 2009 Microchip Technology Inc.Page 1-8 DS01146B
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
Tip #13.1 Reading a Sensor With Higher
Accuracy RC Timing Method
RC Timing Method:
Simple RC step response
Vc(t) = V * (1 - e -t/(RC))dd
t = -RC ln(1 - V /V )th dd
V /V is constantth dd
R2 = (t2/t1) * R1
Figure 13-1
Time
Vc(t)
V
TH
t = 0 t = t1 t = t2
R1 R2
A reference resistor can be used to improve the
accuracy of an analog sensor reading. In this
diagram, the charge time of a resistor/capacitor
combination is measured using a timer and a
port input or comparator input switches from a0’
to1’. The R1 curve uses a reference resistor and
the R2 curve uses the sensor. The charge time
of the R1 curve is known and can be used to
calibrate the unknown sensor reading, R2. This
reduces the affects of temperature, component
tolerance and noise while reading the sensor.
TIP #13 Reading a Sensor With
Higher Accuracy
Sensors can be read directly with the A/D but in
some applications, factors such as temperature,
external component accuracy, sensor non-
linearity and/or decreasing battery voltage need
to be considered. In other applications, more
than 10 bits of accuracy are needed and a
slower sensor read is acceptable. The following
tips deal with these factors and show how to get
the most out of a PIC MCU.
13.1. RC Timing Method (with reference resistor)
13.2. Charge Balancing Method
13.3. A/D Method
© 2009 Microchip Technology Inc. DS01146B-Page 1-9
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
1. Set GP1 and GP2 to inputs, and GP0 to a
low output to discharge C
2. Set GP0 to an input and GP1 to a high output
3. Measure tR (GP0 changes to 1)sen
4. Repeat step 1
5. Set GP0 to an input and GP2 to a high output
6. Measure tR (GP0 changes to 1)ref
7. Use lm polypropylene capacitor
8. R = x R tRth ref sen
tRref
Figure 13-2
PIC12F629
GP0
GP1
GP2
R
REF
R
SEN
Other alternatives: voltage comparator in the
PIC12F6XX to measure capacitor voltage on
GP0.
Application Notes:
AN512, “Implementing Ohmmeter/Temperature
Sensor”
AN611, “Resistance and Capacitance Meter
Using a PIC16C622”
Here is the schematic and software ow for
using a reference resistor to improve the
accuracy of an analog sensor reading. The
reference resistor (R ) and sensor (R ) are ref sen
assigned an I/O and share a common capacitor.
GP0 is used to discharge the capacitor and
represents the capacitor voltage.
Through software, a timer is used to measure
when GP0 switches from a ‘0’ to a ‘1’ for the
sensor and reference measurements. Any
difference measured between the reference
measurement and its calibrated measurement is
used to adjust the sensor reading, resulting in a
more accurate measurement.
The comparator and comparator reference on
the PIC12F629/675 can be used instead of
a port pin for a more accurate measurement.
Polypropylene capacitors are very stable and
benecial in this type of application.
© 2009 Microchip Technology Inc.Page 1-10 DS01146B
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
The comparator and comparator voltage
reference (CVref) on the PIC12F629/675 are
ideal for this application.
1. GP1 average voltage = CVref
2. Time base as sampling rate
3. At the end of each time base period:
- If GP1 > CVref, then GP2 Output Low
- If GP1 < CVref, then GP2 Input mode
4. Accumulate the GP2 lows over many samples
5. Number of samples determines resolution
6. Number of GP2 lows determine effective duty
cycle of Rref
Figure 13-3
PIC12F6XX
RSEN
GP1
GP2
T1G
RREF
VDD
+
-
CVREF
COUT
Tip #13.2 Reading a Sensor With Higher
Accuracy Charge Balancing
Method
1. Sensor charges a capacitor
2. Reference resistor discharges the capacitor
3. Modulate reference resistor to maintain
constant average charge in the capacitor
4. Use comparator to determine modulation
To improve resolution beyond 10 or 12 bits,
a technique called “Charge Balancing” can
be used. The basic concept is for the MCU
to maintain a constant voltage on a capacitor
by either allowing the charge to build through
a sensor or discharge through a reference
resistor. A timer is used to sample the
capacitor voltage on regular intervals until a
predetermined number of samples are counted.
By counting the number of times the capacitor
voltage is over an arbitrary threshold, the sensor
voltage is determined.
© 2009 Microchip Technology Inc.Page 1-12 DS01146B
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIPS ‘N TRICKS WITH SOFTWARE
To reduce costs, designers need to make
the most of the available program memory in
MCUs. Program memory is typically a large
portion of the MCU cost. Optimizing the code
helps to avoid buying more memory than
needed. Here are some ideas that can help
reduce code size.
TIP #15 Delay Techniques
• Use GOTO “next instruction” instead of two
NOPs.
• Use CALL Rtrn as quad, 1 instruction NOP
(where “Rtrn” is the exit label from existing
subroutine).
Example 15-1
NOP
NOP
GOTO $+1
CALL Rtrn ;1 instruction, 4 cycles
Rtrn RETURN
. . .
;2 instructions, 2 cycles
;1 instruction, 2 cycles
MCUs are commonly used to interface with the
“outside world” by means of a data bus, LEDs,
buttons, latches, etc. Because the MCU runs at
a xed frequency, it will often need delay
routines to meet setup/hold times of other
devices, pause for a handshake or decrease the
data rate for a shared bus.
Longer delays are well-suited for the DECFSZ
and INCFSZ instructions where a variable is
decremented or incremented until it reaches
zero when a conditional jump is executed. For
shorter delays of a few cycles, here a few ideas
to decrease code size.
For a two-cycle delay, it is common to use
two NOP instructions which uses two program
memory locations. The same result can
be achieved by using “goto $+1”. The “$”
represents the current program counter value
in MPASM™ Assembler. When this instruction
is encountered, the MCU will jump to the next
memory location. This is what it would have
done if two NOP’s were used but since the
GOTO instruction uses two instruction cycles
to execute, a two-cycle delay was created.
This created a two-cycle delay using only one
location of program memory.
To create a four-cycle delay, add a label to an
existing RETURN instruction in the code. In
this example, the label “Rtrn” was added to the
RETURN of subroutine that already existed
somewhere in the code. When executing “CALL
Rtrn”, the MCU delays two instruction cycles
to execute the CALL and two more to execute
the RETURN. Instead of using four NOP
instructions to create a four-cycle delay, the
same result was achieved by adding a single
CALL instruction.
© 2009 Microchip Technology Inc. DS01146B-Page 1-13
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIP #16 Optimizing Destinations
• Destination bit determines W for F for result
• Look at data movement and restructure
Example 16-1
Example: A + B A
MOVF
ADDWF
MOVWF
MOVF
ADDWF
A,W
B,W
A
B,W
A,F
3 instructions 2 instructions
Careful use of the destination bits in instructions
can save program memory. Here, register A and
register B are summed and the result is put into
the A register. A destination option is available
for logic and arithmetic operations. In the rst
example, the result of the ADDWF instruction is
placed in the working register. A MOVWF
instruction is used to move the result from the
working register to register A. In the second
example, the ADDWF instruction uses the
destination bit to place the result into the A
register, saving an instruction.
TIP #17 Conditional Bit Set/Clear
• To move single bit of data from REGA to
REGB
• Precondition REGB bit
• Test REGA bit and x REGB if necessary
Example 17-1
BTFSS
BCF
BTFSC
BSF
BCF
BTFSC
BSF
REGA,2
REGB,5
REGA,2
REGB,5
REGB,5
REGA,2
REGB,5
4 instructions 3 instructions
One technique for moving one bit from the
REGA register to REGB is to perform bit tests.
In the rst example, the bit in REGA is tested
using a BTFSS instruction. If the bit is clear,
the BCF instruction is executed and clears the
REGB bit, and if the bit is set, the instruction
is skipped.The second bit test determines if
the bit is set, and if so, will execute the BSF
and set the REGB bit, otherwise the instruction
is skipped. This sequence requires four
instructions.
A more efcient technique is to assume the
bit in REGA is clear, and clear the REGB bit,
and test if the REGA bit is clear. If so, the
assumption was correct and the BSF instruction
is skipped, otherwise the REGB bit is set.
The sequence in the second example uses
three instructions because one bit test was not
needed.
One important point is that the second example
will create a two-cycle glitch if REGB is a port
outputting a high. This is caused by the BCF
and BTFSC instructions that will be executed
regardless of the bit value in REGA.
© 2009 Microchip Technology Inc.Page 1-14 DS01146B
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIP #18 Swap File Register with W
Example 18-1
SWAPWF MACRO REG
XORWF REG,F
XORWF REG,W
XORWF REG,F
ENDM
The following macro swaps the contents of W
and REG without using a second register.
Needs: 0 TEMP registers
3 Instructions
3 TCY
An efcient way of swapping the contents of a
register with the working register is to use three
XORWF instructions. It requires no temporary
registers and three instructions. Here’s an
example:
W REG Instruction
10101100 01011100 XORWF REG,F
10101100 11110000 XORWF REG,W
01011100 11110000 XORWF REG,F
01011100 10101100 Result
TIP #19 Bit Shifting Using Carry Bit
Rotate a byte through carry without using RAM
variable for loop count:
• Easily adapted to serial interface transmit
routines.
• Carry bit is cleared (except last cycle) and the
cycle repeats until the zero bit sets indicating
the end.
Example 19-1
bsf
rlf
bcf
btfsc
bsf
bcf
rlf
movf
btfss
goto
LIST P=PIC12f629
INCLUDE P12f629.INC
buffer
STATUS,C
buffer,f
GPIO,Dout
STATUS,C
GPIO,Dout
STATUS,C
buffer,f
buffer,f
STATUS,Z
Send_Loop
equ 0x20
;Set 'end of loop' flag
;Place first bit into C
;precondition output
;Check data 0 or 1 ?
;Clear data in C
;Place next bit into C
;Force Z bit
;Exit?
© 2009 Microchip Technology Inc. DS01146B-Page 2-1
PIC
®
Microcontroller Low Power Tips ‘n Tricks
Table Of Contents
GENERAL LOW POWER TIPS ‘N TRICKS
TIP #1 Switching Off External Circuits/
Duty Cycle .......................................... 2-2
TIP #2 Power Budgeting ................................ 2-3
TIP #3 Conguring Port Pins ......................... 2-4
TIP #4 Use High-Value Pull-Up Resistors ...... 2-4
TIP #5 Reduce Operating Voltage ................. 2-4
TIP #6 Use an External Source for
CPU Core Voltage .............................. 2-5
TIP #7 Battery Backup for PIC MCUs ........... 2-6
DYNAMIC OPERATION TIPS ‘N TRICKS
TIP #8 Enhanced PIC16 Mid-Range Core ..... 2-6
TIP #9 Two-Speed Start-Up ........................... 2-7
TIP #10 Clock Switching .................................. 2-7
TIP #11 Use Internal RC Oscillators ................ 2-7
TIP #12 Internal Oscillator Calibration ............. 2-8
TIP #13 Idle and Doze Modes ......................... 2-8
TIP #14 Use and Idle Mode ...................... 2-9NOP
TIP #15 Peripheral Module Disable
(PMD) Bits .......................................... 2-9
STATIC POWER REDUCTION TIPS ‘N TRICKS
TIP #16 Deep Sleep Mode ...............................2-10
TIP #17 Extended WDT and Deep
Sleep WDT .........................................2-10
TIP #18 Low Power Timer1 Oscillator
and RTCC........................................... 2-10
TIP #19 Low Power Timer1 Oscillator Layout 2-11 ..
TIP #20 Use LVD to Detect Low Battery .......... 2-11
TIP #21 Use Peripheral FIFO and DMA ........... 2-11
TIP #22 Ultra Low-Power
Wake-Up Peripheral ........................... 2-12
TIPSN TRICKS INTRODUCTION
Microchip continues to provide innovative
products that are smaller, faster, easier to
use and more reliable. The Flash-based PIC ®
microcontrollers (MCUs) are used in an wide
range of everyday products, from smoke
detectors, hospital ID tags and pet containment
systems, to industrial, automotive and medical
products.
PIC MCUs featuring nanoWatt technology
implement a variety of important features which
have become standard in PIC microcontrollers.
Since the release of nanoWatt technology,
changes in MCU process technology and
improvements in performance have resulted in
new requirements for lower power. PIC MCUs
with nanoWatt eXtreme Low Power (nanoWatt
XLP™) improve upon the original nanoWatt
technology by dramatically reducing static
power consumption and providing new exibility
for dynamic power management.
The following series of Tips n’ Tricks can be
applied to many applications to make the most
of PIC MCU nanoWatt and nanoWatt XLP
devices.
GENERAL LOW POWER TIPS ‘N
TRICKS
The following tips can be used with all PIC
MCUs to reduce the power consumption of
almost any application.
CHAPTER 2
PIC ® Microcontroller Low Power
Tips ‘n Tricks
© 2009 Microchip Technology Inc.Page 2-2-DS01146B
PIC
®
Microcontroller Low Power Tips ‘n Tricks
TIP #1 Switching Off External
Circuits/Duty Cycle
All the low power modes in the world won’t help
your application if you are unable to control
the power used by circuits external to the
microprocessor. Lighting an LED is equivalent
to running most PIC MCUs at 5V-20 MHz.
When you are designing your circuitry, decide
what physical modes or states are required and
partition the electronics to shutdown unneeded
circuitry.
Figure: 1-1
Y1
PIC16F819
32.768 kHz
0.1 Fµ
C2
33 pF
33 pF
C5
C4
R4
R5
10k
10k
U1
R3
1k
22 pF
C3
R1
100k
R2
100k
C1
0.1 Fµ
3.3V
Serial EEPROM
U2
A0
A1
A2
GND
VCC
WP
SCL
SDA
RB0/INT
RB1
RB2
RB3
RB4
RB5
RB6
RB7
VDD
RA0
RA1
RA2
RA3
RA4/ CKITO
OSC1/CLKIN
OSC2/CLKOUT
VSS
MCLR
The system shown above is very simple
and clearly has all the parts identied in the
requirements. Unfortunately, it has a few
problems in that the EEPROM, the sensor, and
its bias circuit, are energized all the time. To
get the minimum current draw for this design,
it would be advantageous to shutdown these
circuits when they are not required.
Figure: 1-2
Example:
The application is a long duration data recorder.
It has a sensor, an EEPROM, a battery and a
microprocessor. Every two seconds, it must
take a sensor reading, scale the sensor data,
store the scaled data in EEPROM and wait for
the next sensor reading.
In Figure 1-2, I/O pins are used to power the
EEPROM and the sensor. Many PIC MCU
devices can source up to 20 mA of current
from each I/O, so there is no need to provide
additional components to switch the power.
If more current than can be sourced by the PIC
MCU is required, the PIC MCU can instead
enable and disable a MOSFET to power
the circuit. Refer to the data sheet for drive
capabilities for a specic device.
Serial EEPROM
U2
A0
A1
A2
GND
VCC
WP
SCL
SDA
0.1 Fµ
C2
33 pF
C5
32.768 kHz
C4
33 pF
R4
10k
R5
10k
PIC16F819
RB0/INT
RB1
RB2
RB3
RB4
RB5
RB6
RB7
V
DD
RA0
RA1
RA2
RA3
RA4/ CKITO
OSC1/CLKIN
OSC2/CLKOUT
V
SS
MCLR
1k
R3
R2
100k
22 pF
C3
R1
100k
C1
0.1 Fµ
3.3V
U1
Y1
© 2009 Microchip Technology Inc. DS01146B-Page 2-3
PIC
®
Microcontroller Low Power Tips ‘n Tricks
TIP #2 Power Budgeting
Power budgeting is a technique that is critical to
predicting current consumption and battery life.
Power budgeting is performed by calculating
the total charge for each mode of operation
of an application by multiplying that mode’s
current consumption by the time in the mode
for a single application loop. The charge for
each mode is added, then averaged over the
total loop time to get average current. Table 1
calculates a power budget using the application
from Figure 2 in Tip #1 using a typical nanoWatt
XLP device.
Mode
Time
in
Mode
(mS)
Current (mA) Charge
Current *
Time
(mA * Sec)
By
Device
Mode
Total
Sleep
MCU Sleep
Sensor Off
EEPROM Off
1989 5.00E-05 9.95E-05
0.00005
0
0
Initialize
MCU Sleep
Sensor On
EEPROM Off
1 1.66E-02 1.66E-05
0.00005
0.0165
0
Sample Sensor
MCU Run
Sensor On
EEPROM Off
1 6.45E-02 6.45E-05
0.048
0.0165
0
Scaling
MCU Run
Sensor Off
EEPROM Off
1 4.80E-02 4.80E-05
0.048
0
0
Storing
MCU Run
Sensor Off
EEPROM On
8 1.05E+00 8.38E-03
0.048
0
1
Total 2000 8.61E-03
Average Current
= 8.61e-3
2000e-3
mA*Sec
Sec
= 0.0043 mA
Peak Current 1.05 mA
Computing Battery Life
Using the average current from the calculated
power budget, it is possible to determine
how long a battery will be able to power the
application. Table 2 shows lifetimes for typical
battery types using the average power from
Table 1.
Battery Capacity
(mAh)
Life
Hours Days Months Years
CR1212 18 4180 174 5.8 .48
CR1620 75 17417 726 24.2 1.99
CR2032 220 51089 2129 71.0 5.83
Alkaline AAA 1250 290276 12095 403.2 33.14
Alkaline AA 2890 671118 27963 932.1 76.61
Li-ion* 850 197388 8224 274.1 22.53
NOTE: Calculations are based on average current draw only and
do not include battery self-discharge.
*Varies by size; value used is typical.
After completing a power budget, it is very easy
to determine the battery size required to meet
the application requirements. If too much power
is consumed, it is simple to determine where
additional effort needs to be placed to reduce
the power consumption.
© 2009 Microchip Technology Inc.Page 2-4-DS01146B
PIC
®
Microcontroller Low Power Tips ‘n Tricks
TIP #3 Conguring Port Pins
All PIC MCUs have bidirectional I/O pins. Some
of these pins have analog input capabilities. It
is very important to pay attention to the signals
applied to these pins so the least amount of
power will be consumed.
Unused Port Pins
If a port pin is unused, it may be left
unconnected but congured as an output pin
driving to either state (high or low), or it may
be congured as an input with an external
resistor (about 10 kΩ) pulling it to Vdd or V . ss
If congured as an input, only the pin input
leakage current will be drawn through the
pin (the same current would ow if the pin
was connected directly to V or V ). Both dd ss
options allow the pin to be used later for either
input or output without signicant hardware
modications.
Digital Inputs
A digital input pin consumes the least amount
of power when the input voltage is near V dd
or V . If the input voltage is near the midpoint ss
between V and V , the transistors inside the dd ss
digital input buffer are biased in a linear region
and they will consume a signicant amount
of current. If such a pin can be congured as
an analog input, the digital buffer is turned off,
reducing both the pin current as well as the total
controller current.
Analog Inputs
Analog inputs have a very high-impedance
so they consume very little current. They
will consume less current than a digital input
if the applied voltage would normally be
centered between V and V . Sometimes it dd ss
is appropriate and possible to congure digital
inputs as analog inputs when the digital input
must go to a low power state.
Digital Outputs
There is no additional current consumed by a
digital output pin other than the current going
through the pin to power the external circuit.
Pay close attention to the external circuits to
minimize their current consumption.
TIP #4 Use High-Value Pull-Up
Resistors
It is more power efcient to use larger pull-up
resistors on I/O pins such as MCLR, I 2C™
signals, switches and for resistor dividers. For
example, a typical I 2C pull-up is 4.7k. However,
when the I 2C is transmitting and pulling a line
low, this consumes nearly 700 uA of current for
each bus at 3.3V. By increasing the size of the
I2C pull-ups to 10k, this current can be halved.
The tradeoff is a lower maximum I 2C bus
speed, but this can be a worthwhile trade in for
many low power applications. This technique is
especially useful in cases where the pull-up can
be increased to a very high resistance such as
100k or 1M.
TIP #5 Reduce Operating Voltage
Reducing the operating voltage of the device,
V , is a useful step to reduce the overall dd
power consumption. When running, power
consumption is mainly inuenced by the clock
speed. When sleeping, the most signicant
factor is leakage in the transistors. At lower
voltages, less charge is required to switch the
system clocks and transistors leak less current.
It is important to pay attention to how reducing
the operating voltage reduces the maximum
allowed operating frequency. Select the
optimum voltage that allows the application
to run at its maximum speed. Refer to the
device data sheet for the maximum operating
frequency of the device at the given voltage.
© 2009 Microchip Technology Inc. DS01146B-Page 2-5
PIC
®
Microcontroller Low Power Tips ‘n Tricks
TIP #6 Use an External Source for
CPU Core Voltage
Some PIC MCUs such as “J” type devices (ex.
PIC18F87J90 or PIC24FJ64GA004) use sepa-
rate power for CPU core. These devices have
an internal voltage regulator that can be used to
provide the core voltage. Alternatively, the core
voltage can be provided externally by disabling
the internal regulator. In some cases, it is more
power efcient to use an external source for
the core. This is because the internal regula-
tor powers the core at the nominal voltage that
allows full speed operation. However, if an
application doesn’t require full speed, it is ben-
ecial to use lower voltage to power the core.
Disabling the internal regulator also turns off the
BOR and LVD circuits, which saves power as
well. The following examples show two different
battery powered applications where it can be
benecial to disable the internal regulator.
Example 1: Constant Voltage Source
When using a regulated power source or a
battery with a at discharge curve, such as a
lithium coin cell, the regulator can be disabled
and the core powered directly from the battery
through a diode. The diode provides the
voltage drop necessary to power the core at the
correct voltage. It may be necessary to use a
zener diode with a higher forward voltage for
applications using sleep mode, as the current
consumed in sleep is too low to cause the
full forward voltage drop which can result in
applying a voltage too high for the core.
Figure 6-1:
®
Example 2: Non-Constant Voltage Source
If the source for V is not constant, a regulator dd
will be required. It can be benecial to use an
external low quiescent current regulator, which
can be selected to provide lower voltage to the
core than the internal regulator. Additionally,
devices such as the MCP1700, which
consumes 1 uA quiescent current while asleep,
require less power than the internal regulator.
Figure 6-2:
®
© 2009 Microchip Technology Inc.Page 2-6-DS01146B
PIC
®
Microcontroller Low Power Tips ‘n Tricks
TIP #7 Battery Backup for PIC MCUs
For an application that can operate from either
an external supply or a battery backup, it is
necessary to be able to switch from one to
the other without user intervention. This can
be accomplished with battery backup ICs, but
it is also possible to implement with a simple
diode OR circuit, shown in Figure 7-1. Diode D1
prevents current from owing into the battery
from VEXT when the external power is sup-
plied. D2 prevents current from owing into any
external components from the battery if VEXT
is removed. As long as the external source is
present and higher voltage than the battery,
no current from the battery will be used. When
VEXT is removed and the voltage drops below
VBAT, the battery will start powering the MCU.
Low forward voltage Schottky diodes can be
used in order to minimize the voltage dropout
from the diodes. Additionally, inputs can be ref-
erenced to VEXT and VBAT in order to monitor
the voltage levels of the battery and the exter-
nal supply. This allows the micro to enter lower
power modes when the supply is removed or
the battery is running low. In order to avoid
glitches on V caused by the diode turn-on dd
delay when switching supplies, ensure enough
decoupling capacitance is used on V (C1).dd
Figure 7-1:
Dynamic Operation Tips n’ Tricks
The following tips and tricks apply to methods
of improving the dynamic operating current
consumption of an application. This allows
an application to get processing done quicker
which enables it to sleep more and will help
reduce the current consumed while processing.
TIP #8 Enhanced PIC16 Mid-Range
Core
The Enhanced PIC16 mid-range core has a few
features to assist in low power. New instructions
allow many applications to execute in less
time. This allows the application to spend more
time asleep and less time processing and
can provide considerable power savings. It is
important not to overlook these new instructions
when designing with devices that contain the
new core. The Timer1 oscillator and WDT have
also been improved, now meeting nanoWatt
XLP requirements and drawing much less
current than in previous devices.






© 2009 Microchip Technology Inc.Page 2-8-DS01146B
PIC
®
Microcontroller Low Power Tips ‘n Tricks
TIP #12 Internal Oscillator Calibration
An internal RC oscillator calibrated from the
factory may require further calibration as the
temperature or V change. Timer1/SOSC can dd
be used to calibrate the internal oscillator by
connecting a 32.768 kHz clock crystal. Refer
to AN244, “ Internal RC Oscillator Calibration
for the complete application details. Calibrating
the internal oscillator can help save power by
allowing for use of the internal RC oscillator
in applications which normally require higher
accuracy crystals
Figure 12-1: Timer1 Used to Calibrate an
Internal Oscillator
PIC16F818/819
T1OSI
T1OSO
C2
33 pF
C1
33 pF
XTAL
32.768 kHz
The calibration is based on the measured
frequency of the internal RC oscillator. For
example, if the frequency selected is 4 MHz,
we know that the instruction time is 1 µs
(F /4) and Timer1 has a period of 30.5 µs osc
(1/32.768 kHz). This means within one Timer1
period, the core can execute 30.5 instructions.
If the Timer1 registers are preloaded with a
known value, we can calculate the number of
instructions that will be executed upon a Timer1
overow.
This calculated number is then compared
against the number of instructions executed by
the core. With the result, we can determine if
re-calibration is necessary, and if the frequency
must be increased or decreased. Tuning uses
the OSCTUNE register, which has a ±12%
tuning range in 0.8% steps.
TIP #13 Idle and Doze Modes
nanoWatt and nanoWatt XLP devices have
an Idle mode where the clock to the CPU is
disconnected and only the peripherals are
clocked. In PIC16 and PIC18 devices, Idle
mode can be entered by setting the Idle bit in
the OSCON register to ‘ and executing the 1
SLEEP instruction. In PIC24, dsPIC ® DSCs,
and PIC32 devices, Idle mode can be entered
by executing the instruction “ ”. Idle PWRSAV #1
mode is best used whenever the CPU needs to
wait for an event from a peripheral that cannot
operate in Sleep mode. Idle mode can reduce
power consumption by as much as 96% in
many devices.
Doze mode is another low power mode
available in PIC24, dsPIC DSCs, and PIC32
devices. In Doze mode, the system clock to
the CPU is postscaled so that the CPU runs at
a lower speed than the peripherals. If the CPU
is not tasked heavily and peripherals need to
run at high speed, then Doze mode can be
used to scale down the CPU clock to a slower
frequency. The CPU clock can be scaled down
from 1:1 to 1:128. Doze mode is best used in
similar situations to Idle mode, when peripheral
operation is critical, but the CPU only requires
minimal functionality.
© 2009 Microchip Technology Inc. DS01146B-Page 2-9
PIC
®
Microcontroller Low Power Tips ‘n Tricks
TIP #14 Use and Idle ModeNOP
When waiting on a blocking loop (e.g. waiting
for an interrupt), instead put the device into
Idle mode to disable the CPU. The peripheral
interrupt will wake up the device. Idle mode
consumes much less current than constantly
reading RAM and jumping back. If the CPU
cannot be disabled because the loop required
some calculations, such as incrementing a
counter, instead of doing a very tight loop
that loops many times, add s into the NOP
loop. See the code example below. A NOP
requires less current to execute than reading
RAM or branching operations, so current can
be reduced. The overall loop count can be
adjusted to account for the extra instructions for
the s.NOP
Example:
Replace:
while(!_T1IF);
with Idle mode:
IEC0bits.T1IE = 1;
Idle();
and replace:
while(!_T1IF){
i++;
}
with extra NOP instructions:
while(!_T1IF){
i++;
Nop();
Nop();
Nop();
Nop();
Nop();
}
TIP #15 Peripheral Module Disable
(PMD) Bits
PIC24, dsPIC DSCs, and PIC32 devices
have PMD bits that can be used to disable
peripherals that will not be used in the
application. Setting these bits disconnects
all power to the module as well as SFRs for
the module. Because power is completely
removed, the PMD bits offer additional power
savings over disabling the module by turning
off the module’s enable bit. These bits can be
dynamically changed so that modules which are
only used periodically can be disabled for the
remainder of the application. The PMD bits are
most effective at high clock speeds and when
operating at full speed allowing the average
power consumption to be signicantly reduced.
© 2009 Microchip Technology Inc.Page 2-10-DS01146B
PIC
®
Microcontroller Low Power Tips ‘n Tricks
Static Power Reduction Tips n’ Tricks
The following tips and tricks will help reduce
the power consumption of a device while it is
asleep. These tips allow an application to stay
asleep longer and to consume less current
while sleeping.
TIP #16 Deep Sleep Mode
In Deep Sleep mode, the CPU and all
peripherals except RTCC, DSWDT and
LCD (on LCD devices) are not powered.
Additionally, Deep Sleep powers down the
Flash, SRAM, and voltage supervisory circuits.
This allows Deep Sleep mode to have lower
power consumption than any other operating
mode. Typical Deep Sleep current is less than
50 nA on most devices. Four bytes of data are
retained in the DSGPRx registers that can be
used to save some critical data required for the
application. While in Deep Sleep mode, the
states of I/O pins and 32 kHz crystal oscillator
(Timer1/SOSC) are maintained so that Deep
Sleep mode does not interrupt the operation of
the application. The RTCC interrupt, Ultra Low
Power Wake-up, DSWDT time-out, External
Interrupt 0 (INT0), MCLR or POR can wake-up
the device from Deep Sleep. Upon wake-up the
device resumes operation at the reset vector.
Deep Sleep allows for the lowest possible
static power in a device. The trade-off is that
the rmware must re-initialize after wake-
up. Therefore, Deep Sleep is best used in
applications that require long battery life and
have long sleep times. Refer to the device
datasheets and Family Reference Manuals for
more information on Deep Sleep and how it is
used.
TIP #17 Extended WDT and Deep
Sleep WDT
A commonly used source to wake-up from
Sleep or Deep Sleep is the Watchdog Timer
(WDT) or Deep Sleep Watchdog Timer
(DSWDT). The longer the PIC MCU stays
in Sleep or Deep Sleep, the less power
consumed. Therefore, it is appropriate to use
as long a timeout period for the WDT as the
application will allow.
The WDT runs in all modes except for Deep
Sleep. In Deep Sleep, the DSWDT is used
instead. The DSWDT uses less current and
has a longer timeout period than the WDT. The
timeout period for the WDT varies by device,
but typically can vary from a few milliseconds to
up to 2 minutes. The DSWDT time-out period
can be programmed from 2.1ms to 25.7days
TIP #18 Low Power Timer1 Oscillator
and RTCC
nanoWatt XLP microcontrollers all have a
robust Timer1 oscillator (SOSC on PIC24)
which draws less than 800 nA. nanoWatt
technology devices offer a low power Timer1
oscillator which draws 2-3 uA. Some devices
offer a selectable oscillator which can be used
in either a low-power or high-drive strength
mode to suit both low power or higher noise
applications. The Timer1 counter and oscillator
can be used to generate interrupts for periodic
wakes from Sleep and other power managed
modes, and can be used as the basis for a real-
time clock. Timer1/SOSC wake-up options vary
by device. Many nanoWatt XLP devices have a
built-in hardware Real-Time Clock and Calendar
(RTCC), which can be congured for wake-up
periods from 1 second to many years.
Some nanoWatt devices and all nanoWatt
XLP devices can also use the Timer1/SOSC
oscillator as the system clock source in place
of the main oscillator on the OSC1/OSC2 pins.
By reducing execution speed, total current
consumption can be reduced.
© 2009 Microchip Technology Inc. DS01146B-Page 2-11
PIC
®
Microcontroller Low Power Tips ‘n Tricks
TIP #19 Low Power Timer1 Oscillator
Layout
Applications requiring very low power Timer1/
SOSC oscillators on nanoWatt and nanoWatt
XLP devices must take PCB layout into
consideration. The very low power Timer1/
SOSC oscillators on nanoWatt and nanoWatt
XLP devices consume very little current, and
this sometimes makes the oscillator circuit
sensitive to neighboring circuits. The oscillator
circuit (crystal and capacitors) should be located
as close as possible to the microcontroller.
No circuits should be passing through the
oscillator circuit boundaries. If it is unavoidable
to have high-speed circuits near the oscillator
circuit, a guard ring should be placed around the
oscillator circuit and microcontroller pins similar
to the gure below. Placing a ground plane
under the oscillator components also helps to
prevent interaction with high speed circuits.
Figure 19-1: Guard Ring Around Oscillator
Circuit and MCU Pins
VSS
OSC2
OSC1
RB6
RB7
RB5
TIP #20 Use LVD to Detect Low
Battery
The Low Voltage Detect (LVD) interrupt present
in many PIC MCUs is critical in battery based
systems. It is necessary for two reasons.
First, many devices cannot run full speed at
the minimum operating voltage. In this case,
the LVD interrupt indicates when the battery
voltage is dropping so that the CPU clock can
be slowed down to an appropriate speed,
preventing code misexecution. Second, it allows
the MCU to detect when the battery is nearing
the end of its life, so that a low battery indication
can be provided and a lower power state can
be entered to maximize battery lifetime. The
LVD allows these functions to be implemented
without requiring the use of extra analog
channels to measure the battery level.
TIP #21 Use Peripheral FIFO and
DMA
Some devices have peripherals with DMA or
FIFO buffers. These features are not just useful
to improve performance; they can also be used
to reduce power. Peripherals with just one
buffer register require the CPU to stay operating
in order to read from the buffer so it doesn’t
overow. However, with a FIFO or DMA, the
CPU can go to sleep or idle until the FIFO lls or
DMA transfer completes. This allows the device
to consume a lot less average current over the
life of the application.
© 2009 Microchip Technology Inc.Page 2-12-DS01146B
PIC
®
Microcontroller Low Power Tips ‘n Tricks
TIP #22 Ultra Low-Power Wake-Up
Peripheral
Newer devices have a modication to PORTA
that creates an Ultra Low-Power Wake-Up
(ULPWU) peripheral. A small current sink and
a comparator have been added that allows
an external capacitor to be used as a wake-
up timer. This feature provides a low-power
periodic wake-up source which is dependent on
the discharge time of the external RC circuit.
Figure 22-1: Ultra Low-Power Wake-Up
Peripheral
VREF
I
Pin Wake-on-Change
Interrupt
C
If the accuracy of the Watchdog Timer is not
required, this peripheral can save a lot of
current.
Visit the low power design center at:
www.microchip.com/lowpower for
additional design resources.
© 2009 Microchip Technology Inc. DS01146B-Page 3-1
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
Table Of Contents
CAPTURE TIPS ‘N TRICKS
TIP #1 Measuring the Period of a
Square Wave ...................................... 3-3
TIP #2 Measuring the Period of a
Square Wave with Averaging ............. 3-3
TIP #3 Measuring Pulse Width ...................... 3-4
TIP #4 Measuring Duty Cycle ........................ 3-4
TIP #5 Measuring RPM Using an Encoder .... 3-5
TIP #6 Measuring the Period of an
Analog Signal ..................................... 3-6
COMPARE TIPS ‘N TRICKS
TIP #7 Periodic Interrupts .............................. 3-8
TIP #8 Modulation Formats ............................ 3-9
TIP #9 Generating the Time Tick
for a RTOS ......................................... 3-10
TIP #10 16-Bit Resolution PWM ...................... 3-10
TIP #11 Sequential ADC Reader ..................... 3-11
TIP #12 Repetitive Phase Shifted Sampling .... 3-12
PWM TIPS ‘N TRICKS
TIP #13 Deciding on PWM Frequency ............. 3-14
TIP #14 Unidirectional Brushed DC
Motor Control Using CCP ................... 3-14
TIP #15 Bidirectional Brushed DC
Motor Control Using ECCP................. 3-15
TIP #16 Generating an Analog Output ............. 3-16
TIP #17 Boost Power Supply ........................... 3-17
TIP #18 Varying LED Intensity .........................3-18
TIP #19 Generating X-10 Carrier Frequency ... 3-18
COMBINATION CAPTURE AND COMPARE TIPS
TIP #20 RS-232 Auto-baud .............................. 3-19
TIP #21 Dual-Slope Analog-to-Digital
Converter ............................................ 3-21
TIPS ‘N TRICKS INTRODUCTION
Microchip continues to provide innovative
products that are smaller, faster, easier-to-use
and more reliable. PIC® microcontrollers (MCUs)
are used in a wide range of everyday products,
from washing machines, garage door openers
and television remotes to industrial, automotive
and medical products.
The Capture, Compare and PWM (CCP)
modules that are found on many of Microchip’s
microcontrollers are used primarily for the
measurement and control of time-based pulse
signals. The Enhanced CCP (ECCP), available
on some of Microchip’s devices, differs from
the regular CCP module in that it provides
enhanced PWM functionality – namely,
full-bridge and half-bridge support,
programmable dead-band delay and enhanced
PWM auto-shutdown. The ECCP and CCP
modules are capable of performing a wide
variety of tasks. This document will describe
some of the basic guidelines to follow when
using these modules in each mode, as well as
give suggestions for practical applications.
CHAPTER 3
PIC® Microcontroller CCP and ECCP
Tips ‘n Tricks
© 2009 Microchip Technology Inc.Page 3-2-DS01146B
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
ECCP/CCP Register Listing
Capture
Mode
Compare
Mode PWM Mode
CCPxCON Select mode Select mode Select mode,
LSB of duty
cycle
CCPRxL Timer1
capture
(LSB)
Timer1
compare
(LSB)
MSB of duty
cycle
CCPRxH Timer1
capture
(MSB)
Timer1
compare
(MSB)
N/A
TRISx Set CCPx
pin to input
Set CCPx pin
to output
Set CCPx pin(s)
to output(s)
T1CON Timer1 on,
prescaler
Timer1 on,
prescaler
N/A
T2CON N/A N/A Timer2 on,
prescaler
PR2 N/A N/A Timer2 period
PIE1 Timer1
interrupt
enable
Timer1
interrupt
enable
Timer2 interrupt
enable
PIR1 Timer1
interrupt ag
Timer1
interrupt ag
Timer2 interrupt
ag
INTCON Global/
peripheral
interrupt
enable
Global/
peripheral
interrupt
enable
Global/
peripheral
interrupt enable
PWM1CON(1) N/A N/A Set dead band,
auto-restart
control
ECCPAS(1) N/A N/A Auto-shutdown
control
Note 1: Only on ECCP module.
CAPTURE TIPS ‘N TRICKS
In Capture mode, the 16-bit value of Timer1
is captured in CCPRxH:CCPRxL when an
event occurs on pin CCPx. An event is dened
as one of the following and is congured by
CCPxCON<3:0>:
• Every falling edge
• Every rising edge
• Every 4th rising edge
• Every 16th rising edge
“When Would I Use Capture Mode?
Capture mode is used to measure the length of
time elapsed between two events. An event, in
general, is either the rising or falling edge of a
signal (see Figure 1 “Dening Events”).
An example of an application where Capture
mode is useful is reading an accelerometer.
Accelerometers typically vary the duty
cycle of a square wave in proportion to the
acceleration acting on a system. By conguring
the CCP module in Capture mode, the PIC
microcontroller can measure the duty cycle of
the accelerometer with little intervention on the
part of the microcontroller rmware. Tip #4 goes
into more detail about measuring duty cycle by
conguring the CCP module in Capture mode.
Figure 1: Dening Events
Volts
Event: Rising Edge
Event: Falling Edge
Time
© 2009 Microchip Technology Inc. DS01146B-Page 3-3
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #1 Measuring the Period of a
Square Wave
Figure 1-1: Period
T
t1 t2
1. Congure control bits CCPxM3:CCPxM0
(CCPxCON<3:0>) to capture every rising
edge of the waveform.
2. Congure the Timer1 prescaler so Timer1
with run Tmax(1) without overowing.
3. Enable the CCP interrupt (CCPxIE bit).
4. When a CCP interrupt occurs:
a) Subtract saved captured time (t1) from
captured time (t2) and store (use Timer1
interrupt ag as overow indicator).
b) Save captured time (t2).
c) Clear Timer1 ag if set.
The result obtained in step 4.a is the period (T).
Note 1: Tmax is the maximum pulse period
that will occur.
TIP #2 Measuring the Period of a
Square Wave with Averaging
Figure 2-1: Period Measurement
T
t1 t2
16 x T
1. Congure control bits CCPxM3:CCPxM0
(CCPxCON<3:0>) to capture every 16th
rising edge of the waveform.
2. Congure the Timer1 prescaler so Timer1 will
run 16 Tmax(1) without overowing.
3. Enable the CCP interrupt (CCPxIE bit).
4. When a CCP interrupt occurs:
a) Subtract saved captured time (t1) from
captured time (t2) and store (use Timer1
interrupt ag as overow indicator).
b) Save captured time (t2).
c) Clear Timer1 ag if set.
d) Shift value obtained in step 4.a right four
times to divide by 16 – this result is the
period (T).
Note 1: Tmax is the maximum pulse period
that will occur.
The following are the advantages of this
method as opposed to measuring the periods
individually.
• Fewer CCP interrupts to disrupt program ow
• Averaging provides excellent noise immunity
© 2009 Microchip Technology Inc.Page 3-4-DS01146B
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #3 Measuring Pulse Width
Figure 3-1: Pulse Width
W
t1 t2
1. Congure control bits CCPxM3:CCPxM0
(CCPxCON<3:0>) to capture every rising
edge of the waveform.
2. Congure Timer1 prescaler so that Timer1
will run Wmax without overowing.
3. Enable the CCP interrupt (CCPxIE bit).
4. When CCP interrupt occurs, save the
captured timer value (t1) and recongure
control bits to capture every falling edge.
5. When CCP interrupt occurs again, subtract
saved value (t1) from current captured value
(t2) – this result is the pulse width (W).
6. Recongure control bits to capture the next
rising edge and start process all over again
(repeat steps 3 through 6).
TIP #4 Measuring Duty Cycle
Figure 4-1: Duty Cycle
T
W
t1 t2 t3
The duty cycle of a waveform is the ratio
between the width of a pulse (W) and the
period (T). Acceleration sensors, for example,
vary the duty cycle of their outputs based on
the acceleration acting on a system. The CCP
module, congured in Capture mode, can be
used to measure the duty cycle of these types
of sensors. Here’s how:
1. Congure control bits CCPxM3:CCPxM0
(CCPxCON<3:0>) to capture every rising
edge of the waveform.
2. Congure Timer1 prescaler so that Timer1
will run Tmax(1) without overowing.
3. Enable the CCP interrupt (CCPxIE bit).
4. When CCP interrupt occurs, save the
captured timer value (t1) and recongure
control bits to capture every falling edge.
Note 1: Tmax is the maximum pulse period
that will occur.
5. When the CCP interrupt occurs again,
subtract saved value (t1) from current
captured value (t2) – this result is the pulse
width (W).
6. Recongure control bits to capture the next
rising edge.
7. When the CCP interrupt occurs, subtract
saved value (t1) from the current captured
value (t3) – this is the period (T) of the
waveform.
8. Divide T by W – this result is the Duty Cycle.
9. Repeat steps 4 through 8.
© 2009 Microchip Technology Inc. DS01146B-Page 3-5
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #5 Measuring RPM Using an
Encoder
Revolutions Per Minute (RPM), or how fast
something turns, can be sensed in a variety of
ways. Two of the most common sensors used
to determine RPM are optical encoders and
Hall effect sensors. Optical encoders detect the
presence of light shining through a slotted wheel
mounted to a turning shaft (see Figure 5-1.)
As the shaft turns, the slots in the wheel pass
by the eye of the optical encoder. Typically, an
infrared source on the other side of the wheel
emits light that is seen by the optical encoder
through slots in the wheel. Hall effect sensors
work by sensing the position of the magnets in
an electric motor, or by sensing a permanent
magnet mounted to a rotating object (see Figure
5-2). These sensors output one or more pulses
per revolution (depending on the sensor).
Figure 5-1: Optical Encoder
Figure 5-2: Hall Effect Sensor
Slotted
Wheel
IR LED IR Sensor
Front View ie View
Front View ie View
Wheel
Magnet
Magnet
Hall effect
Sensor
In Figure 5-3 and Figure 5-4, the waveform
is high when light is passing through a slot in
the encoder wheel and shining on the optical
sensor. In the case of a Hall effect sensor, the
high corresponds to the time that the magnet is
in front of the sensor. These gures show the
difference in the waveforms for varying RPMs.
Notice that as RPM increases, the period (T)
and pulse width (W) becomes smaller. Both
period and pulse width are proportional to RPM.
However, since the period is the greater of the
two intervals, it is good practice to measure the
period so that the RPM reading from the sensor
will have the best resolution. See Tip #1 for
measuring period. The technique for measuring
period with averaging described in Tip #2 is
useful for measuring high RPMs.
Figure 5-3: Low RPM
Figure 5-4: High RPM
T
W
W
T
© 2009 Microchip Technology Inc.Page 3-6-DS01146B
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #6 Measuring the Period of an
Analog Signal
Microcontrollers with on-board Analog
Comparator module(s), in addition to a CCP
(or ECCP) module, can easily be congured to
measure the period of an analog signal.
Figure 6-1 shows an example circuit using the
peripherals of the PIC16F684.
Figure 6-1: Circuit
PIC16F684
R1
+
R4
R3
R2
V
THR
V
SENSE
-
Comparator
(on-board PIC16F684)
V
OUT
Analog
Input
V
REF
CCP1
R3 and R4 set the threshold voltage for the
comparator. When the analog input reaches
the threshold voltage, Vout will toggle from
low to high. R1 and R2 provide hysteresis to
insure that small changes in the analog input
won’t cause jitter in the circuit. Figure 6-2
demonstrates the effect of hysteresis on the
input. Look specically at what Vsense does
when the analog input reaches the threshold
voltage.
Figure 6-2: Signal Comparison
The CCP module, congured in Capture mode,
can time the length between the rising edges of
the comparator output (Vout.) This is the period
of the analog input, provided the analog signal
reaches V during every period.thr
time
V
THR
V
SENSE
V
OUT
A
nalog
Input
V
THR
time
time
© 2009 Microchip Technology Inc. DS01146B-Page 3-7
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
COMPARE TIPS ‘N TRICKS
In Compare mode, the 16-bit CCPRx register
value is constantly compared against the TMR1
register pair values. When a match occurs, the
CCPx pin is:
• Driven high
• Driven low
• Remains unchanged, or
• Toggles based on the modules conguration
The action on the pin is determined by control
bits CCPxM3:CCPxM0 (CCPxCON<3:0>).
A CCP interrupt is generated when a match
occurs.
Special Event Trigger
Timer1 is normally not cleared during a CCP
interrupt when the CCP module is congured
in Compare mode. The only exception to this is
when the CCP module is congured in Special
Event Trigger mode. In this mode, when Timer1
and CCPRx are equal, the CCPx interrupt
is generated, Timer1 is cleared, and an A/D
conversion is started (if the A/D module is
enabled.)
“Why Would I Use Compare Mode?
Compare mode works much like the timer
function on a stopwatch. In the case of a
stopwatch, a predetermined time is loaded into
the watch and it counts down from that time
until zero is reached.
Compare works in the same way with
one exception – it counts from zero to the
predetermined time. This mode is useful for
generating specic actions at precise intervals.
A timer could be used to perform the same
functionality, however, it would mean preloading
the timer each time. Compare mode also has
the added benet of automatically altering the
state of the CCPx pin based on the way the
module is set up.


Product specificaties

Merk: Microchip
Categorie: Niet gecategoriseerd
Model: PIC24FJ64GA406

Heb je hulp nodig?

Als je hulp nodig hebt met Microchip PIC24FJ64GA406 stel dan hieronder een vraag en andere gebruikers zullen je antwoorden




Handleiding Niet gecategoriseerd Microchip

Handleiding Niet gecategoriseerd

Nieuwste handleidingen voor Niet gecategoriseerd