Microchip PIC24FJ64GU205 Handleiding


Lees hieronder de 📖 handleiding in het Nederlandse voor Microchip PIC24FJ64GU205 (137 pagina's) in de categorie Niet gecategoriseerd. Deze handleiding was nuttig voor 30 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.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. DS01146B-Page 1-11
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIP #14 Delta-Sigma Converter
The charge on the capacitor on GP1 is
maintained about equal to the CVref by the
MCU monitoring C and switching GP2 from out
Input mode or output low appropriately. A timer
is used to sample the C bit on a periodic out
basis. Each time GP2 is driven low, a counter is
incremented. This counter value corresponds to
the input voltage.
To minimize the affects of external component
tolerances, temperature, etc., the circuit can be
calibrated. Apply a known voltage to the input
and allow the microcontroller to count samples
until the expected result is calculated. By taking
the same number of samples for subsequent
measurements, they become calibrated
measurements.
Figure 14-1
C
OUT
V
IN
CV
REF
PIC12F6XX
GP1
GP2
+
-
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 Output High
4. Accumulate the GP2 lows over many
samples
5. Number of samples determines resolution
Tip #13.3 Reading a Sensor With Higher
Accuracy A/D Method
NTC (Negative Temperature Coefcient)
sensors have a non-linear response to
temperature changes. As the temperature
drops, the amount the resistance changes
becomes less and less. Such sensors have
a limited useful range because the resolution
becomes smaller than the A/D resolution as the
temperature drops. By changing the voltage
divider of the R , the temperature range can sen
be expanded.
To select the higher temperature range, GP1
outputs ‘1’ and GP2 is set as an input. For
the lower range, GP2 outputs ‘1’ and GP1
is congured as an input. The lower range
will increase the amount the sensor voltage
changes as the temperature drops to allow a
larger usable sensor range.
Summary:
High range: GP1 output ‘1’ and GP2 input
Low range: GP1 input and GP2 output ‘1’
1. 10K and 100K resistors are used to set the
range
2. Vref for A/D = Vdd
3. Rth calculation is independent of Vdd
4. Count = R /(R +R ) x 255sen sen ref
5. Don’t forget to allow acquisition time for the
A/D
Figure 13-4
PIC12F675
AN0 (A/D Input)
GP1
GP2
100K
10K
R
SEN
© 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, I2C
signals, switches and for resistor dividers. For
example, a typical I2C pull-up is 4.7k. However,
when the I2C 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 I2C 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. DS01146B-Page 2-7
PIC
®
Microcontroller Low Power Tips ‘n Tricks
TIP #9 Two-Speed Start-Up
Two-speed startup is a useful feature on some
nanoWatt and all nanoWatt XLP devices which
helps reduce power consumption by allowing
the device to wake up and return to sleep
faster. Using the internal oscillator, the user can
execute code while waiting for the Oscillator
Start-up (OST) timer to expire (LP, XT or HS
modes). This feature (called “Two-Speed Start-
up”) is enabled using the IESO conguration
bit. A Two-Speed Start-up will clock the device
from an internal RC oscillator until the OST has
expired. Switching to a faster internal oscillator
frequency during start-up is also possible using
the OSCCON register. The example below
shows several stages on how this can be
achieved. The number of frequency changes
is dependent upon the designers discretion.
Assume a 20 MHz crystal (HS Mode) in the
PIC16F example below.
Example:
Tcy
(Instruction Time) Instruction
ORG 0x05 ;Reset vector
125 s @ 32 kHz STATUS,RP0 ;bank1mBSF
125 s @ 32 kHz OSCCON,IRCF2 ;switch to 1 MHzmBSF
4 s @ 1 MHz OSCCON,IRCF1 ;switch to 4 MHzmBSF
1 s @ 4 MHz OSCCON,IRCF0 ;switch to 8 MHzmBSF
500 ns application code
500 ns application code
….
..
(eventually OST expires, 20 MHz crystal clocks the device)
200 ns application code
….
..
TIP #10 Clock Switching
Some nanoWatt devices and all nanoWatt XLP
devices have multiple internal and external
clock sources, as well as logic to allow switching
between the available clock sources as the
main system clock. This allows for signicant
power savings by choosing different clocks
for different portions of code. For example, an
application can use the slower internal oscillator
when executing non-critical code and then
switch to a fast high-accuracy oscillator for time
or frequency sensitive code. Clock switching
allows much more exible applications than
being stuck with a single clock source. Clock
switching sequences vary by device family, so
refer to device data sheets or Family Reference
Manuals for the specic clock switching
sequences.
TIP #11 Use Internal RC Oscillators
If frequency precision better than ±5% is not
required, it is best to utilize the internal RC
oscillators inside all nanoWatt and nanoWatt
XLP devices. The internal RC oscillators have
better frequency stability than external RC
oscillators, and consume less power than
external crystal oscillators. Additionally, the
internal clock can be congured for many
frequency ranges using the internal PLL module
to increase frequency and the postscaler to
reduce it. All these options can be congured in
rmware.
© 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.
© 2009 Microchip Technology Inc.Page 3-8-DS01146B
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
Step #2: Calculate CCPR1 (CCPR1L and
CCPR1H) to shorten the time-out to
exactly 0.2 seconds
a) CCPR1 = Interval Time/(Tosc*4*prescaler) =
0.2/(125 ns*4*8) = 5000 = 0xC350
b) Therefore, CCPR1L = 0x50, and
CCPR1H = 0xC3
Step #3: Conguring CCP1CON
The CCP module should be congured in
Trigger Special Event mode. This mode
generates an interrupt when the Timer1 equals
the value specied in CCPR1L and Timer1
is automatically cleared(1). For this mode,
CCP1CON = ’.b00001011
Note 1: Trigger Special Event mode also
starts an A/D conversion if the
A/D
module is enabled. If this
functionality is not desired, the CCP
module should be congured in
“generate software interrupt-on-
match only” mode (i.e., CCP1CON =
’). Timer 1 must also b 00001010
be cleared manually during the
CCP interrupt.
TIP #7 Periodic Interrupts
Generating interrupts at periodic intervals
is a useful technique implemented in many
applications. This technique allows the main
loop code to run continuously, and then, at
periodic intervals, jump to the interrupt service
routine to execute specic tasks (i.e., read the
ADC). Normally, a timer overow interrupt is
adequate for generating the periodic interrupt.
However, sometimes it is necessary to interrupt
at intervals that can not be achieved with a
timer overow interrupt. The CCP congured
in Compare mode makes this possible by
shortening the full 16-bit time period.
Example Problem:
A PIC16F684 running on its 8 MHz internal
oscillator needs to be congured so that it
updates a LCD exactly 5 times every second.
Step #1: Determine a Timer1 prescaler
that allows an overow at greater
than 0.2 seconds
a) Timer1 overows at: Tosc*4*65536*
prescaler
b) For a prescaler of 1:1, Timer1 overows in
32.8 ms.
c) A prescaler of 8 will cause an overow at a
time greater than 0.2 seconds.
8 x 32.8 ms = 0.25s
© 2009 Microchip Technology Inc. DS01146B-Page 3-9
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #8 Modulation Formats
The CCP module, congured in Compare mode,
can be used to generate a variety of modulation
formats. The following gures show four
commonly used modulation formats:
Figure 8-1: Pulse-width Modulation
Figure 8-2: Manchester
TETE
TBP
Logic
‘ ’0
Logic
‘ ’1
Figure 8-3: Pulse Position Modulation
TETETE
TBP
Logic
‘ ’0
Logic
‘ ’1
T T TE E E
TBP
Logic
‘ ’0
Logic
‘ ’1
Figure 8-4: Variable Pulse-width Modulation
TBP
T TE E
TBP
Logic
‘ ’0
Logic
‘ ’1
Transition Low
to High
Transition High
to Low
TBP
T TE E
TBP
The gures show what a logic ‘0’ or a logic
‘1’ looks like for each modulation format.
A transmission typically resembles an
asynchronous serial transmission consisting of
a Start bit, followed by 8 data bits, and a Stop
bit.
Te is the basic timing element in each
modulation format and will vary based on the
desired baud rate.
Trigger Special Event mode can be used to
generate Te, (the basic timing element). When
the CCPx interrupt is generated, code in the ISR
routine would implement the desired modulation
format (additional modulation formats are also
possible).
© 2009 Microchip Technology Inc.Page 3-10-DS01146B
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #9 Generating the Time Tick for a
RTOS
Real Time Operating Systems (RTOS) require
a periodic interrupt to operate. This periodic
interrupt, or “tick rate”, is the basis for the
scheduling system that RTOS’s employ. For
instance, if a 2 ms tick is used, the RTOS will
schedule its tasks to be executed at multiples
of the 2 ms. A RTOS also assigns a priority to
each task, ensuring that the most critical tasks
are executed rst. Table 9-1 shows an example
list of tasks, the priority of each task and the
time interval that the tasks need to be executed.
Table 9-1: Tasks
Task PriorityInterval
Read ADC Input 1 20 ms 2
Read ADC Input 2 60 ms 1
Update LCD 24 ms 2
Update LED Array 36 ms 3
Read Switch 10 ms 1
Dump Data to Serial Port 240 ms 1
The techniques described in Tip #7 can be used
to generate the 2 ms periodic interrupt using the
CCP module congured in Compare mode.
Note: For more information on RTOSs
and their use, see Application Note
AN777 “Multitasking on the
PIC16F877 with the Salvo™ RTOS”.
TIP #10 16-Bit Resolution PWM
Figure 10-1: 16-Bit Resolution PWM
CCPx Interrupt:
Clear CCPx pin
Timer1 Interrupt:
Set CCPx pin
1. Congure CCPx to clear output (CCPx pin)
on match in Compare mode (CCPxCON
<CCPSM3:CCPxM0>).
2. Enable the Timer1 interrupt.
3. Set the period of the waveform via Timer1
prescaler (T1CON <5:4>).
4. Set the duty cycle of the waveform using
CCPRxL and CCPRxH.
5. Set CCPx pin when servicing the Timer1
overow interrupt(1).
Note 1: One hundred percent duty cycle
is not achievable with this
implementation due to the interrupt
latency in servicing Timer1. The
period is not affected because
the interrupt latency will be the
same from period to period as long
as the Timer1 interrupt is serviced
rst in the ISR.
Timer1 has four congurable prescaler values.
These are 1:1, 1:2, 1:4 and 1:8. The frequency
possibilities of the PWM described above are
determined by Equation 10-1.
Equation 10-1
For a microcontroller running on a 20 MHz
oscillator (Fosc) this equates to frequencies
of 76.3 Hz, 38.1 Hz, 19.1 Hz and 9.5 Hz for
increasing prescaler values.
F = F /(65536*4*prescaler)pwm osc
© 2009 Microchip Technology Inc. DS01146B-Page 3-11
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #11 Sequential ADC Reader
Figure 11-1: Timeline
Time
Read AN0 Read AN1 Read AN2 Read AN0
Trigger Special Event mode (a sub-mode in
Compare mode) generates a periodic interrupt
in addition to automatically starting an A/D
conversion when Timer1 matches CCPRxL and
CCPRxH. The following example problem
demonstrates how to sequentially read the A/D
channels at a periodic interval.
Example
Given the PIC16F684 running on its 8 MHz
internal oscillator, congure the microcontroller
to sequentially read analog pins AN0, AN1 and
AN2 at 30 ms intervals.
Step #1: Determine Timer1 Prescaler
a) Timer1 overows at: Tosc*4*65536*
prescaler.
b) For a prescaler of 1:1, the Timer1 overow
occurs in 32.8 ms.
c) This is greater than 30 ms, so a prescaler of
1 is adequate.
Step #2: Calculate CCPR1 (CCPR1L and
CCPR1H)
a) CCPR1 = Interval Time/(Tosc*4*prescaler) =
0.030/(125 ns*4*1) = 6000 = 0xEA60
b) Therefore, CCPR1L = 0x60, and CCPR1H =
0xEA
Step #3: Conguring CCP1CON
The ECCP module should be congured
in Trigger Special Event mode. This mode
generates an interrupt when Timer1 equals
the value specied in CCPR1. Timer1 is
automatically cleared and the GO bit in
ADCON0 is automatically set. For this mode,
CCP1CON = ‘ ’.b00001011
Step #4: Add Interrupt Service Routine Logic
When the ECCP interrupt is generated, select
the next A/D pin for reading by altering the
ADCON0 register.
© 2009 Microchip Technology Inc. DS01146B-Page 3-13
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
PWM TIPS ‘N TRICKS
The ECCP and CCP modules produce a 10-bit
resolution Pulse-Width Modulated (PWM)
waveform on the CCPx pin. The ECCP module
is capable of transmitting a PWM signal on one
of four pins, designated P1A through P1D. The
PWM modes available on the ECCP module
are:
• Single output (P1A only)
• Half-bridge output (P1A and P1B only)
• Full-bridge output forward
• Full-bridge output reverse
One of the following congurations must be
chosen when using the ECCP module in PWM
Full-bridge mode:
• P1A, P1C active-high; P1B, P1D active-high
• P1A, P1C active-high; P1B, P1D active-low
• P1A, P1C active-low; P1B, P1D active-high
• P1A, P1C active-low; P1B, P1D active-low
“Why Would I Use PWM Mode?”
As the next set of Tips ‘n Tricks demonstrate,
Pulse-Width Modulation (PWM) can be used
to accomplish a variety of tasks from dimming
LEDs to controlling the speed of a brushed DC
electric motor. All these applications are based
on one basic principle of PWM signals –
as the duty cycle of a PWM signal increases,
the average voltage and power provided by
the PWM increases. Not only does it increase
with duty cycle, but it increases linearly. The
following gure illustrates this point more clearly.
Notice that the RMS and maximum voltage are
functions of the duty cycle (DC) in the following
Figure 12-3.
Figure 12-3: Duty Cycle Relation to Vrms
Equation 12-1 shows the relation between Vrms
and V .max
Equation 12-1: Relation Between Vrms max and V
VMAX
VRMS
T
DC = 10%
VRMS
DC = 80%
Vrms max = DCxV
© 2009 Microchip Technology Inc.Page 3-14-DS01146B
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #13 Deciding on PWM Frequency
In general, PWM frequency is application
dependent although two general rules-of-thumb
hold regarding frequency in all applications.
They are:
1. As frequency increases, so does current
requirement due to switching losses.
2. Capacitance and inductance of the load tend
to limit the frequency response of a circuit.
In low-power applications, it is a good idea
to use the minimum frequency possible to
accomplish a task in order to limit switching
losses. In circuits where capacitance and/or
inductance are a factor, the PWM frequency
should be chosen based on an analysis of the
circuit.
Motor Control
PWM is used extensively in motor control
due to the efciency of switched drive
systems as opposed to linear drives. An
important consideration when choosing PWM
frequency for a motor control application is
the responsiveness of the motor to changes
in PWM duty cycle. A motor will have a faster
response to changes in duty cycle at higher
frequencies. Another important consideration
is the sound generated by the motor. Brushed
DC motors will make an annoying whine
when driven at frequencies within the audible
frequency range (20 Hz-4 kHz.) In order to
eliminate this whine, drive brushed DC motors
at frequencies greater than 4 kHz. (Humans
can hear frequencies at upwards of 20 kHz,
however, the mechanics of the motor winding
will typically attenuate motor whine above
4 kHz).
LED and Light Bulbs
PWM is also used in LED and light dimmer
applications. Flicker may be noticeable with
rates below 50 Hz. Therefore, it is generally a
good rule to pulse-width modulate LEDs and
light bulbs at 100 Hz or higher.
TIP #14 Unidirectional Brushed DC
Motor Control Using CCP
Figure 14-1: Brushed DC (BDC) Motor
Control Circuit
PIC16F628
10 kΩ
22 pF
VCC
EMI/RFI
Suppression
Place on
motor
22 pF
Motor
100Ω
CCP1
Figure 14-1 shows a unidirectional speed
controller circuit for a brushed DC motor. Motor
speed is proportional to the duty cycle of the
PWM output on the CCP1 pin. The following
steps show how to congure the PIC16F628 to
generate a 20 kHz PWM with 50% duty cycle.
The microcontroller is running on a 20 MHz
crystal.
Step #1: Choose Timer2 Prescaler
a) F = Fosc/((PR2+1)*4*prescaler) = pwm
19531 Hz for PR2 = 255 and prescaler of 1
b) This frequency is lower than 20 kHz,
therefore a prescaler of 1 is adequate.
Step #2: Calculate PR2
PR2 = Fosc/(F *4*prescaler) – 1 = 249pwm
Step #3: Determine CCPR1L and
CCP1CON<5:4>
a) CCPR1L:CCP1CON<5:4> =
DutyCycle*0x3FF = 0x1FF
b) CCPR1L = 0x1FF >> 2 = 0x7F,
CCP1CON<5:4> = 3
Step #4: Congure CCP1CON
The CCP module is congured in PWM mode
with the Least Signicant bits of the duty cycle
set, therefore, CCP1CON = ‘ ’.b001111000
© 2009 Microchip Technology Inc. DS01146B-Page 3-15
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #15 Bidirectional Brushed DC
Motor Control Using ECCP
Figure 15-1: Full-Bridge BDC Drive Circuit
10 kΩ
TC428
VCC
P1A
10 pF
Motor
10 pF
10 kΩ
P1B
TC428
10 kΩ
TC428
VCC
P1C
10 pF
10 pF
10 kΩ
P1D
TC428
The ECCP module has brushed DC motor
control options built into it. Figure 15-1 shows
how a full-bridge drive circuit is connected
to a BDC motor. The connections P1A, P1B,
P1C and P1D are all ECCP outputs when the
module in congured in “Full-bridge Output
Forward” or “Full-bridge Output Reverse”
modes (CCP1CON<7:6>). For the circuit shown
in Figure 15-1, the ECCP module should be
congured in PWM mode: P1A, P1C active
high; P1B, P1D active high (CCP1CON<3:1>).
The reason for this is the MOSFET drivers
(TC428) are congured so a high input will turn
on the respective MOSFET.
The following table shows the relation between
the states of operation, the states of the ECCP
pins and the ECCP Conguration register.
State P1A P1B P1C P1D CCP1CON
Forward 1 tri-state tri-state mod b01xx1100
Reverse tri-state mod 1 tri-state ‘ b11xx1100
Coast tri-state tri-state tri-state tri-state N/A
Brake tri-state 1 1 tri-state N/A
Legend:
= high, ‘ = low, mod = modulated, tri-state = 1 0
pin congured as input
© 2009 Microchip Technology Inc.Page 3-16-DS01146B
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
R and C are chosen based on the following
equation:
Equation 16-2
Pick a value of C arbitrarily and then calculate
R. The attenuation of the PWM frequency for a
given RC lter is:
Equation 16-3
If the attenuation calculated in Equation 16-3
is not sufcient, then K must be increased in
Equation 16-1. See Application Note AN538
Using PWM to Generate Analog Output in
PIC17C42” for more details on using PWM to
generate an analog output.
TIP #16 Generating an Analog Output
Figure 16-1: Low-Pass Filter
Op Amp
PIC16F684
CCP1 Analog
Out
R
C
+
-
Pulse-width modulated signals can be used to
create Digital-to-Analog (D/A) converters with
only a few external components. Conversion of
PWM waveforms to analog signals involves the
use of an analog low-pass lter. In order to
eliminate unwanted harmonics caused by a
PWM signal to the greatest degree possible, the
frequency of the PWM signal (F ) should be pwm
signicantly higher than the bandwidth (Fbw) of
the desired analog signal. Equation 16-1 shows
this relation.
Equation 16-1
Fpwm = K*Fbw
Where harmonics decrease as K increases
RC = 1/(2 F )p bw
Att(dB = – 10*log[1+(2 F RC)2]p pwm
© 2009 Microchip Technology Inc.Page 3-18-DS01146B
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #18 Varying LED Intensity
The intensity of an LED can be varied by
pulse-width modulating the voltage across
the LED. A microcontroller typically drives an
LED with the circuit shown in Figure 18-1. The
purpose of R1 is to limit the LED current so
that the LED runs in its specied current and
voltage range, typically around 1.4 volts at
20 mA. Modulating the LED drive pin on the
microcontroller will vary the average current
seen by the LED and thus its intensity. As
mentioned in Tip #13, LEDs and other light
sources should be modulated at no less than
100 Hz in order to prevent noticeable icker.
Figure 18-1: LED Drive
PIC16F684
CCP1
R1
270
The CCP module, congured in PWM mode,
is ideal for varying the intensity of an LED.
Adjustments to the intensity of the LED are
made by simply varying the duty cycle of
the PWM signal driving the LED. This is
accomplished by varying the CCPRxL register
between 0 and 0xFF.
TIP #19 Generating X-10 ® Carrier
Frequency
X-10 uses a piggybacked 120 kHz square wave
(at 50% duty cycle) to transmit information over
60 Hz power lines. The CCP module, running
in PWM mode, can accurately create the 120
kHz square wave, referred to as the carrier
frequency. Figure 19-1 shows how the 120
kHz carrier frequency is piggybacked onto the
sinusoidal 60 Hz power waveform.
Figure 19-1: Carrier Frequency With
Sinusoidal Waveform
PIC16F87XA
0.1 Fµ
X2 Rated
200Ω
OSC2
OSC1
RC3/CCP1
120 CVA
7.680 MHz
High-Pass Filter
1 MΩ
50Ω
+5 VDC
X-10 species the carrier frequency at 120 kHz
(± 2 kHz). The system oscillator in Figure 18-1
is chosen to be 7.680 MHz, so that the CCP
module can generate precisely 120 kHz. X-10
requires that the carrier frequency be turned on
and off at different points on the 60 Hz power
waveform. This is accomplished by conguring
the TRIS register for the CCP1 pin as either
an input (carrier frequency off) or an output
(carrier frequency on). Refer to Application
Note AN236 “X-10 Home Automation Using the
PIC16F877A” for more details on X-10 and
for source code for setting up the CCP module
appropriately.
© 2009 Microchip Technology Inc.Page 3-20-DS01146B
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
Example 20-1: Transmit Routine
TxRoun neti
MO reload bit co teVL ;pW 8 un r
;with 8
MOVWF counter
BCF TxLine ;line initially high,
;toggle lo for STARw T
;bit
TxLoop
CA layTLL De b ;wait Tb (bit period)
RRF RxByte,f ;rota LS first inte B to
;the Carry flag
BTFSS STATUS,C ;Tx line state ualseq
;state of rry flagCa
BCF TxLine
BTFSC STATUS,C
BSF TxLine
DE SZ unter,CF Co f ;Repe 8 meat ti s
GO LoopTO Tx
CA lay Tb elay Tb foreLL De ;D be
;sending STOP bit
BSF TxLine ;send STOP bit
Example 20-2: Receive Routine
RxRoutine
BTFSC RxLi ;wait for receivene
;line to go low
GOTO RxRo inut e
MOVLW 8 ;initialize bit
;counter to 8
MOVWF Counter
CALL Dela alfTb;delay 1/2 Tb herey1H
;plus Tb in RxLoop
;in order to sample
;at the ght timeri
RxLoop
CALL DelayTb ;wa Tb (biit t
;period)
BTFSS RxLi ;Carry flag statene
;equals liRx ne
;state
BC USF STAT ,C
BTFSC RxLine
BS USF STAT ,C
BTFSC RxLine
BS USF STAT ,C
RR teF RxBy ,f ;Rotate LSB first
;into receive type
DECFSZ Coun r,te f ;Repeat time8 s
GOTO RxLoop
© 2009 Microchip Technology Inc. DS01146B-Page 4-1
PIC
®
Microcontroller Comparator Tips ‘n Tricks
Table Of Contents
TIPS ‘N TRICKS INTRODUCTION
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
TIPS ‘N 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 a
wide range of everyday products from smoke
detectors to industrial, automotive and medical
products.
The PIC12F/16F Family of devices with on-chip
voltage comparators merge all the advantages
of the PIC MCU architecture and the exibility
of Flash program memory with the mixed signal
nature of a voltage comparator. Together they
form a low-cost hybrid digital/analog building
block with the power and exibility to work in an
analog world.
The exibility of Flash and an excellent
development tool suite, including a low-
cost In-Circuit Debugger, In-Circuit Serial
Programming™ (ICSP™) and MPLAB® ICE
2000 emulation, make these devices ideal for
just about any embedded control application.
The following series of Tips ‘n Tricks can be
applied to a variety of applications to help
make the most of discrete voltage comparators
or microcontrollers with on-chip voltage
comparators.
CHAPTER 4
PIC® Microcontroller Comparator
Tips ‘n Tricks
© 2009 Microchip Technology Inc.Page 4-2-DS01146B
PIC
®
Microcontroller Comparator Tips ‘n Tricks
Figure 1-2: Unregulated Supply
+
-
R1
Low Battery
Enable
R2
R3
D1
V
BATT
Comparator
Comparator will trip when V = 3V: R1 = 33k, batt
R2 = 10k and R3 = 470Ω.
In Figure 1-2, resistor R3 is chosen to bias
diode D1 above its forward voltage when V batt
is equal to the minimum battery voltage for the
system. Resistors R1 and R2 are chosen to set
the inverting input voltage equal to the forward
voltage of D1.
TIP #1 Low Battery Detection
When operating from a battery power supply, it
is important for a circuit to be able to determine
when the battery charge is insufcient for
normal operation of the circuit. Typically, this
is a comparator-based circuit similar to the
Programmable Low Voltage Detect (PLVD)
peripheral. If the PLVD peripheral is not
available in the microcontroller, a similar circuit
can be constructed using a comparator and a
few external components (see Figure 1-1 and
Figure 1-2). The circuit in Figure 1-1 assumes
that the microcontroller is operating from a
regulated supply voltage. The circuit in Figure
1-2 assumes that the microcontroller supply is
unregulated.
Figure 1-1: Regulated Supply
+
-
R1
Low Battery
Enable
R2
R3
R4
V
DD
V
BATT
The comparator will trip when the battery
voltage, V = 5.7V: R1 = 33k, R2 = 10k, batt
R3 = 39k, R4 = 10k, V = 5V.dd
In Figure 1-1, resistors R1 and R2 are chosen
to place the voltage at the non-inverting input
at approximately 25% of Vdd. R3 and R4
are chosen to set the inverting input voltage
equal to the non-inverting input voltage when
the battery voltage is equal to the minimum
operating voltage for the system.
© 2009 Microchip Technology Inc. DS01146B-Page 4-3
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #2 Faster Code for Detecting
Change
When using a comparator to monitor a sensor,
it is often just as important to know when
a change occurs as it is to know what the
change is. To detect a change in the output of
a comparator, the traditional method has been
to store a copy of the output and periodically
compare the held value to the actual output to
determine the change. An example of this type
of routine is shown below.
Example 2-1
Test
MOVF hold,w ;get old Cout
XORWF CMCON,w ;compare to new Cout
ANDLW COUTMASK
BTFSC STATUS,Z
RETLW 0 ;if = return "no change"
MOVF CMCON,w ;if not =, get new Cout
ANDLW COUTMASK ;remove all other bits
MOVWF hold ;store in holding var.
IORLW CHNGBIT ;add change flag
RETURN
This routine requires 5 instructions for each test,
9 instructions if a change occurs, and 1 RAM
location for storage of the old output state.
A faster method for microcontrollers with a
single comparator is to use the comparator
interrupt ag to determine when a change has
occurred.
Example 2-2
Test
BTFSS PIR1,CMIF ;test comparator flag
RETLW 0 ;if clear, return a 0
BTFSS CMCON,COUT ;test Cout
RETLW CHNGBIT ;if clear return
;CHNGFLAG
RETLW COUTMASK + CHNGBIT;if set,
;return both
This routine requires 2 instructions for each test,
3 instructions if a change occurs, and no RAM
storage.
If the interrupt ag can not be used, or if two
comparators share an interrupt ag, an alternate
method that uses the comparator output polarity
bit can be used.
Example 2-3
Test
BTFSS CMCON,COUT ;test Cout
RETLW 0 ;if clear, return 0
MOVLW CINVBIT ;if set, invert Cout
XORWF CMCON,f ;forces Cout to 0
BTFSS CMCON,CINV ;test Cout polarity
RETLW CHNGFLAG ;if clear, return
;CHNGFLAG
RETLW COUTMASK + CHNGFLAG;if set,
;return both
This routine requires 2 instructions for each test,
5 instructions if a change occurs, and no GPR
storage.
© 2009 Microchip Technology Inc. DS01146B-Page 4-11
PIC
®
Microcontroller Comparator Tips ‘n Tricks
Figure 10-2: Equivalent Output Model
VOUT
ROUT
2 x VDD
To design a voltage doubler, rst determine the
maximum tolerable output resistance based on
the required output current and the minimum
tolerable output voltage. Remember that the
output current will be limited to one half of
the output capability of the comparator. Then
choose a transfer capacitance and switching
frequency using Equation 10-1.
Equation 10-1
Note: Rout will be slightly higher due to
the dynamic resistance of the diodes.
The equivalent series resistance or
ESR, of the capacitors and the
output resistance of the comparator.
See the TC7660 data sheet for a
more complete description.
Once the switching frequency is determined,
design a square-wave multi-vibrator as
described in Tip #8.
Finally, select diodes D1 and D2 for their current
rating and set C2 equal to C1.
Example:
From Tip #8, the values are modied for a Fosc
of 4.8 kHz.
• C1 and C2 = 10 mF
• Rout = 21W
TIP #10 Capacitive Voltage Doubler
This tip takes the multi-vibrator described in
Tip #8 and builds a capacitive voltage doubler
around it (see Figure 10-1). The circuit works
by alternately charging capacitor C1 through
diode D1, and then charge balancing the energy
in C1 with C2 through diode D2. At the start
of the cycle, the output of the multi-vibrator is
low and charge current ows from Vdd through
D1 and into C1. When the output of the multi-
vibrator goes high, D1 is reverse biased and the
charge current stops. The voltage across C1 is
added to the output voltage of the multi-vibrator,
creating a voltage at the positive terminal of C1
which is 2 x Vdd. This voltage forward biases D2
and the charge in C1 is shared with C2. When
the output of the multi-vibrator goes low again,
the cycle starts over.
Figure 10-1: Capacitive Voltage Doubler
V
OLT
D2
V
DD
+
-
RT
Comparator
R2
R3
CT
R1 C2
D1
V
DD
+
+
C1
Note: The output voltage of a capacitive
double is unregulated and will sag
with increasing load current.
Typically, the output is modeled as a
voltage source with a series
resistance (see Figure 10-2).
Rout = 1
F
swi tch
* C1
© 2009 Microchip Technology Inc.Page 4-12-DS01146B
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #11 PWM Generator
This tip shows how the multi-vibrator (ramp wave)
can be used to generate a voltage controlled
PWM signal. The ramp wave multi-vibrator
operates as described in Tip #9, generating a
positive going ramp wave. A second comparator
compares the instantaneous voltage of the ramp
wave with the incoming voltage to generate the
PWM output (see Figure 11-2).
When the ramp starts, it is below the input
voltage, and the output of the second
comparator is pulled high starting the PWM
pulse. The output remains high until the ramp
wave voltage exceeds the input, then the output
of the second comparator goes low ending
the PWM pulse. The output of the second
comparator remains low for the remainder of
the ramp waveform. When the ramp waveform
returns to zero at the start of the next cycle, the
second comparator output goes high again and
the cycle starts over.
Figure 11-1: PWM Wave Forms
Ramp
Wave
Form
V1
Time
Output
Input
Time
Time
Figure 11-2: PWM Circuit
+
-
CLD
Comparator
R2
R3
CT
R1
V
DD
D1
Input +
-Comparator
Output
V1
To design a PWM generator, start with the
design of a ramp wave multi-vibrator using the
design procedure from Tip #9. Choose high and
low threshold voltages for the multi-vibrators
hysteresis feedback that are slightly above and
below the desired PWM control voltages.
Note: The PWM control voltage will
produce a 0% duty cycle for inputs
below the low threshold of the
multi-vibrator. A control voltage
greater than the high threshold
voltage will produce a 100% duty
cycle output.
Using the example values from Tip #9 will result
in a minimum pulse width at an input voltage of
1.7V and a maximum at an input of 3.2V.


Product specificaties

Merk: Microchip
Categorie: Niet gecategoriseerd
Model: PIC24FJ64GU205

Heb je hulp nodig?

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




Handleiding Niet gecategoriseerd Microchip

Handleiding Niet gecategoriseerd

Nieuwste handleidingen voor Niet gecategoriseerd