Compiled Tips ‘N Tricks Guide

Microchip Technology

View All Related Products | Download PDF Datasheet

Datasheet

© 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, KEELOQ, KEELOQ 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 committed to continuously improving the code protection features of 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: Vd d Self Starting Circuit ............................. 1-7
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
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 Configuring 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 NOP and Idle Mode .............................. 2-9
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 Rectifier 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: Vd d Self Starting Circuit.................... 1-7
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 flexibility 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 flexibility 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 flow 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
12 5
4
3
6
GP0
GP1
GP2
© 2009 Microchip Technology Inc. DS01146B-Page 1-3
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIP #3 Read Three States
From One Pin
To check state Z:
• Drive output pin high
• Set to Input
• Read 1
• Drive output pin low
• Set to Input
• Read 0
To check state 0:
• Read 0 on pin
To check state 1:
• Read 1 on pin
State Link 0 Link 1
0 closed open
1 open closed
NC open open
Jumper has three possible states: not
connected, Link 1 and Link 0. The capacitor
will charge and discharge depending on
the I/O output voltage allowing the “not
connected” state. Software should check the
“not connected” state first by driving I/O high,
reading 1 and driving I/O low and reading 0. The
“Link 1” and “Link 0” states are read directly.
PIC
I/O
5V
0V
Link 0
Link 1
Figure 3-1
TIP #4 Reading DIP Switches
The input of a timer
can be used to test
which switch(s)
is closed. The
input of Timer1 is
held high with a
pull-up resistor.
Sequentially,
each switch I/O is
set to input and
Timer1 is checked
for an increment
indicating the
switch is closed.
Each bit in the DP register represents its
corresponding switch position. By setting
Timer1 to FFFFh and enabling its interrupt, an
increment will cause a rollover and generate
an interrupt. This will simplify the software by
eliminating the bit test on the TMR1L register.
Sequentially set each GPIO to an input and test
for TMR1 increment (or 0 if standard I/O pin is
used).
Figure 4-1
PIC12F6XX
GP0
GP1
GP2
GP3
GP5/T1CKI
10K
V
DD
GP4Data I/O
movlw b'11111111'
movwf TRISIO
movwf DIP
movlw b'00000111'
movwf T1CON
movlw b'11111110'
movwf Mask
clrf GPIO
LOOP
clrf TMR1L
movf Mask,W
movwf TRISIO
btfsc TMR1L,0
andwf DIP,F
bsf STATUS,C
rlf Mask,F
btfsc Mask,4
goto Loop
retlw 0
Example 4-1
© 2009 Microchip Technology Inc.Page 1-4 DS01146B
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIP #5 Scanning Many Keys With
One Input
The time required to charge a capacitor
depends on resistance between Vd d and
capacitor. When a button is pressed, Vd d is
supplied to a different point in the resistor
ladder. The resistance between Vd d and the
capacitor is reduced, which reduces the charge
time of the capacitor. A timer is used with a
comparator or changing digital input to measure
the capacitor charge time. The charge time is
used to determine which button is pressed.
Software sequence:
1. Configure GP2 to output a low voltage to
discharge capacitor through I/O resistor.
2. Configure GP2 as one comparator input and
CVr e f as the other.
3. Use a timer to measure when the comparator
trips. If the time measured is greater than the
maximum allowed time, then repeat;
otherwise determine which button is pressed.
When a key is pressed, the voltage divider
network changes the RC ramp rate.
Figure 5-1
PIC12F6XX
GP0
GP1
GP2
GP4
GP5
GP3
16
Resistors
220
R
R
R
R
See AN512, “Implementing Ohmmeter/
Temperature Sensor” for code ideas.
TIP #6 Scanning Many Keys and
Wake-up From Sleep
An additional I/O can be added to wake the
part when a button is pressed. Prior to Sleep,
configure GP1 as an input with interrupt-on-
change enabled and GP2 to output high. The
pull-down resistor holds GP1 low until a button
is pressed. GP1 is then pulled high via GP2
and Vd d generating an interrupt. After wake-up,
GP2 is configured to output low to discharge
the capacitor through the 220Ω resistor. GP1 is
set to output high and GP2 is set to an input to
measure the capacitor charge time.
• GP1 pin connected to key common
• Enable wake-up on port change
• Set GP1 as input and GP2 high prior to Sleep
• If key is pressed the PIC MCU wakes up, GP2
must be set low to discharge capacitor
• Set GP1 high upon wake-up to scan keystroke
Figure 6-1
VDD 100R
PIC12F6XX
GP0
GP1
GP2
GP4
GP5
GP3
220
R
R
R
R
16
Resistors
© 2009 Microchip Technology Inc. DS01146B-Page 1-5
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIP #7 4x4 Keyboard with 1 Input
By carefully selecting the resistor values,
each button generates a unique voltage. This
voltage is measured by the A/D to determine
which button is pressed. Higher precision
resistors should be used to maximize voltage
uniqueness. The A/D will read near 0 when no
buttons are pressed.
Figure 7-1
V
DD
PIC12F6XX
GP0
TIP #8 One Pin Power/Data
A single I/O can be used for both a single-
direction communication and the power source
for another microcontroller. The I/O line is held
high by the pull-up resistor connected to Vd d .
The sender uses a pull-down transistor to pull
the data line low or disables the transistor to
allow the pull-up to raise it to send data to the
receiver. Vd d is supplied to the sender through
the data line. The capacitor stabilizes the sender’s
Vd d and a diode prevents the capacitor from
discharging through the I/O line while it is low.
Note that the Vd d of the sender is a diode-drop
lower than the receiver.
Figure 8-1
V
DD
V
DD
Receiver
GP0 GP0
Sender
V
DD
- 0.7V
© 2009 Microchip Technology Inc.Page 1-6 DS01146B
8-pin Flash PIC
®
Microcontroller Tips ‘n Tricks
TIP #9 Decode Keys and ID Settings
Buttons and jumpers can share I/O’s by using
another I/O to select which one is read. Both
buttons and jumpers are tied to a shared
pull-down resistor. Therefore, they will read
as ‘0’ unless a button is pressed or a jumper
is connected. Each input (GP3/2/1/0) shares
a jumper and a button. To read the jumper
settings, set GP4 to output high and each
connected jumper will read as ‘1’ on its assigned
I/O or ‘0’ if it’s not connected. With GP4 output
low, a pressed button will be read as ‘1’ on its
assigned I/O and ‘0’ otherwise.
Figure 9-1
V
DD
GP0
GP1
GP2
GP3
GP4
• When GP4 = 1 and no keys are pressed, read
ID setting
• When GP4 = 0, read the switch buttons
TIP #10 Generating High Voltages
Figure 10-1
PIC12F6XX
w/RC CLKOUT
CPUMP CFILTER
CLKOUT
VOUT max = 2 * VDD - 2 * VDIODE
VDD
Voltages greater than Vd d can be generated
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 Vd d diode is forward
biased and conducts current, thereby charging
Cp u m p . After OSC2 is high, the other diode is
forward biased, moving the charge to Cf i l t e r .
The result is a charge equal to twice the Vd d
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 Vd d Self Starting Circuit
Building on the previous topic, the same charge
pump can be used by the MCU to supply its
own Vd d . Before the switch is pressed, Vb a t
has power and the Vd d points are connected
together but unpowered. When the button is
pressed, power is supplied to Vd d and the
MCUs CLKOUT (in external RC oscillator mode)
begins toggle. The voltage generated by the
charge pump turns on the FET allowing Vd d
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 filter capacitor
• Varying levels of overcurrent response can be
realized in software
By adding a resistor (Rs e n s e ) in series with a
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) = Vd d * (1 - e -t/(RC))
t = -RC ln(1 - Vt h /Vd d )
Vt h /Vd d is constant
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 a ‘0’
to ‘1’. 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 tRs e n (GP0 changes to 1)
4. Repeat step 1
5. Set GP0 to an input and GP2 to a high output
6. Measure tRr e f (GP0 changes to 1)
7. Use film polypropylene capacitor
8. Rt h = x Rr e f tRs e n
tRr e f
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 flow for
using a reference resistor to improve the
accuracy of an analog sensor reading. The
reference resistor (Rr e f ) and sensor (Rs e n ) are
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
beneficial 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 (CVr e f ) on the PIC12F629/675 are
ideal for this application.
1. GP1 average voltage = CVr e f
2. Time base as sampling rate
3. At the end of each time base period:
- If GP1 > CVr e f , then GP2 Output Low
- If GP1 < CVr e f , 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 Rr e f
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 CVr e f by the
MCU monitoring Co u t and switching GP2 from
Input mode or output low appropriately. A timer
is used to sample the Co u t bit on a periodic
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 = CVr e f
2. Time base as sampling rate
3. At the end of each time base period:
- If GP1 > CVr e f , then GP2 Output Low
- If GP1 < CVr e f , 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 Coefficient)
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 Rs e n , the temperature range can
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 configured 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. Vr e f for A/D = Vd d
3. Rth calculation is independent of Vd d
4. Count = Rs e n /(Rs e n +Rr e f ) x 255
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 fixed 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 first
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 fix 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 first 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 efficient 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 efficient 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 Configuring 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 NOP and Idle Mode ...................... 2-9
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
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 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 flexibility
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
The system shown above is very simple
and clearly has all the parts identified 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 specific device.
© 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 Configuring 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 configured as an output pin
driving to either state (high or low), or it may
be configured as an input with an external
resistor (about 10 kΩ) pulling it to Vd d or Vs s .
If configured as an input, only the pin input
leakage current will be drawn through the
pin (the same current would flow if the pin
was connected directly to Vd d or Vs s ). Both
options allow the pin to be used later for either
input or output without significant hardware
modifications.
Digital Inputs
A digital input pin consumes the least amount
of power when the input voltage is near Vd d
or Vs s . If the input voltage is near the midpoint
between Vd d and Vs s , the transistors inside the
digital input buffer are biased in a linear region
and they will consume a significant amount
of current. If such a pin can be configured 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 Vd d and Vs s . Sometimes it
is appropriate and possible to configure 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 efficient 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,
Vd d , is a useful step to reduce the overall
power consumption. When running, power
consumption is mainly influenced by the clock
speed. When sleeping, the most significant
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 efficient 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-
eficial 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
beneficial to disable the internal regulator.
Example 1: Constant Voltage Source
When using a regulated power source or a
battery with a flat 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 Vd d is not constant, a regulator
will be required. It can be beneficial 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 flowing into the battery
from VEXT when the external power is sup-
plied. D2 prevents current from flowing 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 Vd d caused by the diode turn-on
delay when switching supplies, ensure enough
decoupling capacitance is used on Vd d (C1).
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 configuration
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 designer’s discretion.
Assume a 20 MHz crystal (HS Mode) in the
PIC16F example below.
Example:
Tc y
(Instruction Time) Instruction
ORG 0x05 ;Reset vector
125 ms @ 32 kHz BSF STATUS,RP0 ;bank1
125 ms @ 32 kHz BSF OSCCON,IRCF2 ;switch to 1 MHz
4 ms @ 1 MHz BSF OSCCON,IRCF1 ;switch to 4 MHz
1 ms @ 4 MHz BSF OSCCON,IRCF0 ;switch to 8 MHz
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 significant
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 flexible 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 specific 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 configured for many
frequency ranges using the internal PLL module
to increase frequency and the postscaler to
reduce it. All these options can be configured in
firmware.
© 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 Vd d change. Timer1/SOSC can
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
(Fo s c /4) and Timer1 has a period of 30.5 µs
(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
overflow.
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 ‘1 and executing the
SLEEP instruction. In PIC24, dsPIC® DSCs,
and PIC32 devices, Idle mode can be entered
by executing the instruction “PWRSAV #1”. Idle
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 NOP and Idle Mode
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 NOPs into the
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 NOPs.
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 significantly 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 firmware 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 configured 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 figure 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
overflow. However, with a FIFO or DMA, the
CPU can go to sleep or idle until the FIFO fills 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 modification 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 flag
Timer1
interrupt flag
Timer2 interrupt
flag
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 defined
as one of the following and is configured 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 “Defining 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 configuring
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 firmware. Tip #4 goes
into more detail about measuring duty cycle by
configuring the CCP module in Capture mode.
Figure 1: Defining 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. Configure control bits CCPxM3:CCPxM0
(CCPxCON<3:0>) to capture every rising
edge of the waveform.
2. Configure the Timer1 prescaler so Timer1
with run Tm a x (1) without overflowing.
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 flag as overflow indicator).
b) Save captured time (t2).
c) Clear Timer1 flag if set.
The result obtained in step 4.a is the period (T).
Note 1: Tm a x 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. Configure control bits CCPxM3:CCPxM0
(CCPxCON<3:0>) to capture every 16th
rising edge of the waveform.
2. Configure the Timer1 prescaler so Timer1 will
run 16 Tm a x (1) without overflowing.
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 flag as overflow indicator).
b) Save captured time (t2).
c) Clear Timer1 flag 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: Tm a x 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 flow
• 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. Configure control bits CCPxM3:CCPxM0
(CCPxCON<3:0>) to capture every rising
edge of the waveform.
2. Configure Timer1 prescaler so that Timer1
will run Wm a x without overflowing.
3. Enable the CCP interrupt (CCPxIE bit).
4. When CCP interrupt occurs, save the
captured timer value (t1) and reconfigure
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. Reconfigure 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, configured in Capture mode, can be
used to measure the duty cycle of these types
of sensors. Here’s how:
1. Configure control bits CCPxM3:CCPxM0
(CCPxCON<3:0>) to capture every rising
edge of the waveform.
2. Configure Timer1 prescaler so that Timer1
will run Tm a x (1) without overflowing.
3. Enable the CCP interrupt (CCPxIE bit).
4. When CCP interrupt occurs, save the
captured timer value (t1) and reconfigure
control bits to capture every falling edge.
Note 1: Tm a x 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. Reconfigure 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 figures 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 configured 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, Vo u t 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 specifically at what Vs e n s e does
when the analog input reaches the threshold
voltage.
Figure 6-2: Signal Comparison
The CCP module, configured in Capture mode,
can time the length between the rising edges of
the comparator output (Vo u t .) This is the period
of the analog input, provided the analog signal
reaches Vt h r during every period.
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 module’s configuration
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 configured
in Compare mode. The only exception to this is
when the CCP module is configured 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 specific 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 benefit 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/(To s c *4*prescaler) =
0.2/(125 ns*4*8) = 5000 = 0xC350
b) Therefore, CCPR1L = 0x50, and
CCPR1H = 0xC3
Step #3: Configuring CCP1CON
The CCP module should be configured in
Trigger Special Event mode. This mode
generates an interrupt when the Timer1 equals
the value specified 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 configured in
“generate software interrupt-on-
match only” mode (i.e., CCP1CON =
b00001010’). Timer 1 must also
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 specific tasks (i.e., read the
ADC). Normally, a timer overflow 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 overflow interrupt. The CCP configured
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 configured so that it
updates a LCD exactly 5 times every second.
Step #1: Determine a Timer1 prescaler
that allows an overflow at greater
than 0.2 seconds
a) Timer1 overflows at: Tosc*4*65536*
prescaler
b) For a prescaler of 1:1, Timer1 overflows in
32.8 ms.
c) A prescaler of 8 will cause an overflow 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, configured in Compare mode,
can be used to generate a variety of modulation
formats. The following figures show four
commonly used modulation formats:
Figure 8-1: Pulse-width Modulation
Figure 8-2: Manchester
T
E
T
E
T
BP
Logic
0
Logic
1
Figure 8-3: Pulse Position Modulation
T
E
T
E
T
E
T
BP
Logic
0
Logic
1
TETETE
TBP
Logic
0
Logic
1
Figure 8-4: Variable Pulse-width Modulation
TBP
TETE
TBP
Logic
0
Logic
1
Transition Low
to High
Transition High
to Low
TBP
TETE
TBP
The figures 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 first. 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 Interval Priority
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 configured 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. Configure 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
overflow 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
first in the ISR.
Timer1 has four configurable 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.
Fp w m = Fo s c /(65536*4*prescaler)
© 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, configure the microcontroller
to sequentially read analog pins AN0, AN1 and
AN2 at 30 ms intervals.
Step #1: Determine Timer1 Prescaler
a) Timer1 overflows at: Tosc*4*65536*
prescaler.
b) For a prescaler of 1:1, the Timer1 overflow
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: Configuring CCP1CON
The ECCP module should be configured
in Trigger Special Event mode. This mode
generates an interrupt when Timer1 equals
the value specified 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.Page 3-12-DS01146B
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #12 Repetitive Phase Shifted
Sampling
Repetitive phase shifted sampling is a technique
to artificially increase the sampling rate of an
A/D converter when sampling waveforms that
are both periodic and constant from period
to period. The technique works by capturing
regularly spaced samples of the waveform
from the start to finish of the waveform’s
period. Sampling of the next waveform is then
performed in the same manner, except that
the start of the sample sequence is delayed a
percentage of the sampling period. Subsequent
waveforms are also sampled, with each sample
sequence slightly delayed from the last, until
the delayed start of the sample sequence is
equal to one sample period. Interleaving the
sample sets then produces a sample set of
the waveform at a higher sample rate. Figure
12-1 shows an example of a high frequency
waveform.
Figure 12-1: High Frequency Periodic
Waveform
IA
As indicated in the key, the finely dotted lines
show where the A/D readings are taken during
the first period of the waveform. The medium
sized dashed lines show when the A/D readings
are taken during the second period, and so on.
Figure 12-2 shows these readings transposed
onto one period.
Figure 12-2: Transposed Waveform
I
V
Time
First Pass
Second Pass
Third Pass
Fourth Pass
Key
Volts
The CCP module is configured in Compare
Special Event Trigger mode to accomplish this
task. The phase shift is implemented by picking
values of CCPRxL and CCPRxH that are not
synchronous with the period of the sampling
waveform. For instance, if the period of a
waveform is 100 ms, then sampling at a rate of
once every 22 µs will give the following set of
sample times over 11 periods (all values in µs).
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th
0 10 20 8 18 6 16 4 14 2 12
22 32 42 30 40 28 38 26 36 24 34
44 54 64 52 62 50 60 48 58 46 56
66 76 86 74 84 72 82 70 80 68 78
88 98 96 94 92 90
When these numbers are placed in sequential
order, they reveal a virtual sampling interval (Iv)
of 2 ms from 0 ms to 100 ms, although the actual
sampling interval (Ia) is 22 ms.
© 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 configurations 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 figure 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 Vr m s
Equation 12-1 shows the relation between Vr m s
and Vm a x .
Equation 12-1: Relation Between Vr m s and Vm a x
VMAX
VRMS
T
DC = 10%
VRMS
DC = 80%
Vr m s = DCxVm a x
© 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 efficiency 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
CCP1
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 configure 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) Fp w m = Fosc/((PR2+1)*4*prescaler) =
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/(Fp w m *4*prescaler) – 1 = 249
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: Configure CCP1CON
The CCP module is configured in PWM mode
with the Least Significant 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
V
CC
P1A
10 pF
Motor
10 pF
10 k
P1B
TC428
10 k
TC428
V
CC
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 configured 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
configured in PWM mode: P1A, P1C active
high; P1B, P1D active high (CCP1CON<3:1>).
The reason for this is the MOSFET drivers
(TC428) are configured 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 Configuration 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:
1 = high, ‘0’ = low, mod = modulated, tri-state =
pin configured 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 filter is:
Equation 16-3
If the attenuation calculated in Equation 16-3
is not sufficient, 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 filter. In order to
eliminate unwanted harmonics caused by a
PWM signal to the greatest degree possible, the
frequency of the PWM signal (Fp w m ) should be
significantly higher than the bandwidth (Fb w ) of
the desired analog signal. Equation 16-1 shows
this relation.
Equation 16-1
Fp w m = K*Fb w
Where harmonics decrease as K increases
RC = 1/(2pFb w )
Att(dB = – 10*log[1+(2pFp w m RC)2]
© 2009 Microchip Technology Inc. DS01146B-Page 3-17
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #17 Boost Power Supply
Figure 17-1: Boost Power Supply Circuit
D1
VIN
PIC16F684
CCP1
Feedback
C2
47 µF
VCC
C1
10 µF
R1
4.7 k
L1
680 µH
Q1
R3
10 k
VOUT
RL
AN0
Hardware
Pulse-width modulation plays a key role in
boost power supply design. Figure 17-1 shows
a typical boost circuit. The circuit works by Q1
grounding the inductor (L1) during the high
phase of the PWM signal generated by CCP1.
This causes an increasing current to flow
through L1 while Vc c is applied. During the low
phase of the PWM signal, the energy stored in
L1 flows through D1 to the storage capacitor
(C2) and the load. Vo u t is related to Vi n by
Equation 17-1.
Note: Technical Brief TB053 “Generating
High Voltage Using the PIC16C781/
782” provides details on boost power
supply design.
The first parameter to determine is the duty
cycle based upon the input and output voltages.
See Equation 17-1.
Equation 17-1
Next, the value of the inductor is chosen based
on the maximum current required by the load,
the switching frequency and the duty cycle. A
function for inductance in terms of load current
is given by Equation 17-2, where T is the PWM
period, D is the duty cycle, and Io u t is the
maximum load current.
Equation 17-2
The value for L is chosen arbitrarily to satisfy
this equation given Io u t , a maximum duty cycle
of 75% and a PWM frequency in the 10 kHz to
100 kHz range.
Using the value chosen for L, the ripple current
is calculated using Equation 17-3.
Equation 17-3
Ir i p p l e can not exceed the saturation current for
the inductor. If the value for L does produce a
ripple current greater than Is a t , a bigger inductor
is needed.
Note: All equations above assume a
discontinuous current mode.
Firmware
The PWM duty cycle is varied by the
microcontroller in order to maintain a stable
output voltage over fluctuating load conditions.
A firmware implemented PID control loop is
used to regulate the duty cycle. Feedback from
the boost power supply circuit provides the input
to the PID control.
Note: Application Note AN258 “Low Cost
USB Microcontroller Programmer
provides details on firmware-based
PID control.
Ir i p p l e = Vi n DT
L
L = Vi n (1 - D) Dt
2 Io u t
Vo u t = 1
Vi n 1 - D
© 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 specified 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 flicker.
Figure 18-1: LED Drive
PIC16F684
CCP1
R1
270
The CCP module, configured 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 VAC
7.680 MHz
High-Pass Filter
1 M
50
+5 VDC
X-10 specifies 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 configuring
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. DS01146B-Page 3-19
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
COMBINATION CAPTURE AND
COMPARE TIPS
The CCP and ECCP modules can be
configured on the fly. Therefore, these modules
can perform different functions in the same
application provided these functions operate
exclusively (not at the same time). This section
will provide examples of using a CCP module in
different modes in the same application.
TIP #20 RS-232 Auto-baud
RS-232 serial communication has a variety
of baud rates to choose from. Multiple
transmission rates require software which
detects the transmission rate and adjusts the
receive and transmit routines accordingly.
Auto-baud is used in applications where
multiple transmission rates can occur. The CCP
module can be configured in Capture mode to
detect the baud rate and then be configured in
Compare mode to generate or receive RS-232
transmissions.
In order for auto-baud to work, a known
calibration character must be transmitted initially
from one device to another. One possible
calibration character is show in Figure 20-1.
Timing this known character provides the
device with the baud rate for all subsequent
communications.
Figure 20-1: RS-232 Calibration Character
Start
Bit Stop
Bit
LSB MSB
0 0 0 0 0 0 01
Auto-baud Routine Implementation:
1. Configure CCP module to capture the falling
edge (beginning of Start bit).
2. When the falling edge is detected, store the
CCPR1 value.
3. Configure the CCP module to capture the
rising edge.
4. Once the rising edge is detected, store the
CCPR1 value.
5. Subtract the value stored in step 2 from the
value in step 4. This is the time for 8 bits.
6. Shift the value calculated in step 5 right 3
times to divide by 8. This result is the period
of a bit (Tb).
7. Shift value calculated in step 6 right by 1.
This result is half the period of a bit.
The following code segments show the process
for transmitting and receiving data in the normal
program flow. This same functionality can
be accomplished using the CCP module by
configuring the module in Compare mode and
generating a CCP interrupt every bit period.
When this method is used, one bit is either sent
or received when the CCP interrupt occurs.
Note: Refer to Application Note AN712
RS-232 Auto-baud for the PIC16C5X
Devices” for more details on
auto-baud.
© 2009 Microchip Technology Inc.Page 3-20-DS01146B
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
Example 20-1: Transmit Routine
TxRounti ne
MOVL W8 ;p reload bit coun ter
;w ith 8
MOVW Fcounter
BCF TxLine ;line initially high,
;t oggle low for START
;b it
TxLoop
CALL De layTb ;wait Tb (bit period)
RRF RxByte, f;rotate LSB first into
;t he Carry flag
BTFS SSTATUS, C;Tx line state eq uals
;s tate of Ca rry flag
BCF TxLine
BTFS CSTATUS, C
BSF TxLine
DECF SZ Co unter,f;Repeat 8 ti mes
GOTO Tx Loop
CALL De lay Tb ;D elay Tb be fore
;s ending STOP bit
BSF TxLine ;send STOP bit
Example 20-2: Receive Routine
RxRoutine
BTFSC RxLine ;wait for receive
;line to go low
GOTO RxRout ine
MOVLW 8 ;initialize bit
;counter to 8
MOVWF Counte r
CALL Delay1 HalfTb;delay 1/2 Tb here
;plus Tb in RxLoop
;in order to sample
;at the ri ght time
RxLoop
CALL DelayT b ;wait Tb (bit
;period)
BTFSS RxLine ;Carry flag state
;equals Rx line
;state
BC FSTATUS ,C
BTFSC RxLine
BS FSTATUS ,C
BTFSC RxLine
BS FSTATUS ,C
RR FRxByte ,f ;Rotate LSB first
;into receive type
DECFSZ Counte r,f ;Repeat 8 times
GOTO RxLoop
© 2009 Microchip Technology Inc. DS01146B-Page 3-21
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #21 Dual-Slope Analog-to-Digital
Converter
A circuit for performing dual-slope A/D
conversion utilizing the CCP module is shown in
Figure 21-1.
Figure 21-1: Dual-Slope Analog-to-Digital
Converter
V
IN
Comparator
(on-board PIC16F684)
+
-
+
-
Integrator
-V
REF
CCP1
PIC16F684
Dual-slope A/D conversion works by integrating
the input signal (Vi n ) for a fixed time (T1). The
input is then switched to a negative reference
(-Vr e f ) and integrated until the integrator output
is zero (T2). Vi n is a function of Vr e f and the
ratio of T2 to T1.
Figure 21-2: V vs. Time
Time
VIN
Integrator output
with VIN input
V
VIN
Integrator output
with VREF input
T1
T1 T2
T2
The components of this conversion type are
the fixed time and the timing of the falling edge.
The CCP module can accomplish both of these
components via Compare mode and Capture
mode respectively. Here’s how:
1. Configure the CCP module in Compare
mode, Special Event Trigger.
2. Switch the analog input into the integrator
from Vr e f to Vi n .
3. Use the CCP module to wait T1 (T1 chosen
based on capacitor value).
4. When the CCP interrupt occurs, switch the
analog input into the regulator from Vi n to
Vr e f and reconfigure the module in Capture
mode; wait for falling edge.
5. When the next CCP interrupt occurs, the time
captured by the module is T2.
6. Calculate Vi n using Equation 21-1.
Equation 21-1
Vi n = Vr e f T2
T1
© 2009 Microchip Technology Inc.Page 3-22-DS01146B
PIC
®
Microcontroller CCP and ECCP Tips ‘n Tricks
NOTES:
© 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 flexibility
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 flexibility to work in an
analog world.
The flexibility 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 Vb a t t = 3V: R1 = 33k,
R2 = 10k and R3 = 470Ω.
In Figure 1-2, resistor R3 is chosen to bias
diode D1 above its forward voltage when Vb a t t
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 insufficient 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, Vb a t t = 5.7V: R1 = 33k, R2 = 10k,
R3 = 39k, R4 = 10k, Vd d = 5V.
In Figure 1-1, resistors R1 and R2 are chosen
to place the voltage at the non-inverting input
at approximately 25% of Vd d . 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 flag 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 flag can not be used, or if two
comparators share an interrupt flag, 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.Page 4-4-DS01146B
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #3 Hysteresis
When the voltages on a comparator’s input are
nearly equal, external noise and switching noise
from inside the microcontroller can cause the
comparator output to oscillate or “chatter.” To
prevent chatter, some of the comparator output
voltage is fed back to the non-inverting input of
the comparator to form hysteresis (see Figure
3-1). Hysteresis moves the comparator
threshold up when the input is below the
threshold, and down when the input is above
the threshold. The result is that the input must
overshoot the threshold to cause a change
in the comparator output. If the overshoot is
greater than the noise present on the input, the
comparator output will not chatter.
Figure 3-1: Comparator with Hysteresis
Input
V
DD
+
-
R2
R3
R1
Output
To calculate the resistor values required, first
determine the high and low threshold values
which will prevent chatter (Vt h and Vt l ). Using
Vt h and Vt l , the average threshold voltage can
be calculated using the equation.
Equation 3-1
Next, choose resistor values that satisfy
Equation 3-2 and calculate the equivalent
resistance using Equation 3-3.
Note: A continuous current will flow through
R1 and R2. To limit the power
dissipation in R1 and R2 the total
resistance of R1 and R2 should be at
least 1k. The total resistance of R1
and R2 should also be kept below
10K to keep the size of R3 small.
Large values for R3, 100k-10 M
W
,
can produce voltage offsets at the
non-inverting input due to the
comparator’s input bias current.
Equation 3-2
Equation 3-3
Then, determine the feedback divider ratio Dr,
using Equation 3-4.
Equation 3-4
Finally, calculate the feedback resistor R3 using
Equation 3-5.
Equation 3-5
Example:
• A Vd d = 5.0V, Vh = 3.0V and Vl = 2.5V
• Va v g = 2.77V
• R = 8.2k and R2 = 10k, gives a Va v g = 2.75V
• Re q = 4.5k
• Dr = .1
• R3 = 39k (40.5 calculated)
• Vh a c t = 2.98V
• Vl a c t = 2.46V
R3 = Re q [ ( 1 ) - 1]
Dr
Va v g = Vd d * R2
R1 + R2
Re q = R1 * R2
R1 + R2
Dr = (Vt h - Vt l )
Vd d
Va v g = Vd d * Vt l
Vd d - Vt h + Vt l
© 2009 Microchip Technology Inc. DS01146B-Page 4-5
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #4 Pulse Width Measurement
To measure the high or low pulse width of an
incoming analog signal, the comparator can
be combined with Timer1 and the Timer1 Gate
input option (see Figure 4-1). Timer1 Gate acts
as a count enable for Timer1. If the input is
low, Timer1 will count. If the T1G input is high,
Timer1 does not count. Combining T1G with the
comparator allows the designer to measure the
time between a high-to-low output change and a
low-to-high output change.
To make a measurement between a low-to-high
and a high-to-low transition, the only change
required is to set the CINV bit in the comparator
CMCON register which inverts the comparator
output.
Because the output of the comparator can
change asynchronously with the Timer1 clock,
only comparators with the ability to synchronize
their output with the Timer1 clock should be
used and their C2SYNC bits should be set.
Figure 4-1: Comparator with Timer1 and T1G
+
-
Trigger
Level
V
DD
V
INPUT
C
OUT
Timer1
TIG
If the on-chip comparator does not have the
ability to synchronize its output to the Timer1
clock, the output can be synchronized externally
using a discrete D flip-flop (see Figure 4-2).
Note: The flip-flop must be falling edge
triggered to prevent a race condition.
Figure 4-2: Externally Synchronized
Comparator
+
-
Trigger
Level
V
DD
V
INPUT
C
OUT
Timer1
TIG
Timer
Clock T1CKI
DO
© 2009 Microchip Technology Inc.Page 4-6-DS01146B
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #5 Window Comparison
When monitoring an external sensor, it is often
convenient to be able to determine when the
signal has moved outside a pre-established
safe operating range of values or window of
operation. This windowing provides the circuit
with an alarm when the signal moves above or
below safety limits, ignoring minor fluctuations
inside the safe operating range.
To implement a window comparator, two voltage
comparators and 3 resistors are required (see
Figure 5-1).
Figure 5-1: Window Comparator
Resistors R1, R2 and R3 form a voltage divider
which generates the high and low threshold
voltages. The outputs HIGH LIMIT and LOW
LIMIT are both active high, generating a logic
one on the HIGH LIMIT output when the input
voltage rises above the high threshold, and a
logic one on the LOW LIMIT output when the
input voltage falls below the low threshold.
To calculate values for R1, R2 and R3, find
values that satisfy Equation 5-1 and Equation
5-2.
Note:
A continuous current will flow
through R1, R2 and R3. To limit the
power dissipation in the resistors, the
total resistance of R1, R2 and R3
should be at least 1k. The total
resistance of R1, R2 and R3 should
also be kept less than 1
M
W to
prevent offset voltages due to the
input bias currents of the comparator.
Equation 5-1
Equation 5-2
Example:
• Vd d = 5.0V, Vt h = 2.5V, Vt l = 2.0V
• R1 = 12k, R2 = 2.7k, R3 = 10k
• Vt h (actual) = 2.57V, Vt l (actual) = 2.02V
Adding Hysteresis:
To add hysteresis to the HIGH LIMIT
comparator, follow the procedure outlined in
Tip #3. Use the series combination of R2 and
R3 as the resistor R2 in Tip #3.
To add hysteresis to the LOW LIMIT
comparator, choose a suitable value for Req,
1k to 10 k
W
, and place it between the circuit
input and the non-inverting input of the LOW
LIMIT comparator. Then calculate the needed
feedback resistor using Equation 3-4 and
Equation 3-5.
V
DD
R2
+
-
+
-
R1
R3
Input
Low Limit
High Limit
Vt h -h i = Vd d * (R3 +R2)
R1 + R2 + R3
Vt h -l o = Vd d * R3
R1 + R2 + R3
© 2009 Microchip Technology Inc. DS01146B-Page 4-7
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #6 Data Slicer
In both wired and wireless data transmission,
the data signal may be subject to DC offset
shifts due to temperature shifts, ground
currents or other factors in the system. When
this happens, using a simple level comparison
to recover the data is not possible because
the DC offset may exceed the peak-to-peak
amplitude of the signal. The circuit typically
used to recover the signal in this situation is a
data slicer.
The data slicer shown in Figure 6-1 operates
by comparing the incoming signal with a sliding
reference derived from the average DC value
of the incoming signal. The DC average value
is found using a simple RC low-pass filter (R1
and C1). The corner frequency of the RC filter
should be high enough to ignore the shifts in
the DC level while low enough to pass the data
being transferred.
Resistors R2 and R3 are optional. They provide
a slight bias to the reference, either high or low,
to give a preference to the state of the output
when no data is being received. R2 will bias the
output low and R3 will bias the output high. Only
one resistor should be used at a time, and its
value should be at least 50 to 100 times larger
than R1.
Figure 6-1: Data Slicer
+
-
R2
R3
Input
VDD
Output
Comparator
C1
R1
Example:
Data rate of 10 kbits/second. A low pass filter
frequency of 500 Hz: R1 = 10k, C1 = 33 mF. R2
or R3 should be 500k to 1 MB.
© 2009 Microchip Technology Inc.Page 4-8-DS01146B
PIC
®
Microcontroller Comparator Tips ‘n Tricks
When the voltage across C1 exceeds the high
threshold voltage, the output of the comparator
goes low, C1 is discharged to just above the
0.7V limit, the non-inverting input is pulled below
0.7V, and the circuit is reset for the next pulse
input, waiting for the next trigger input.
Figure 7-1: One-Shot Circuit
R3
Input
D1
C2
V2
R2
VDD
V1
VDD Output
+
-
R1
Comparator
R5
R4
C1
To design the one-shot, first create the
hysteresis feedback using the techniques from
Tip #3. Remember to set the low threshold
below 0.7V. Next, choose values for R2 and C1
using Equation 7-1.
Equation 7-1
D1 can be any low voltage switching diode. R1
should be 1% to 2% of R2 and C2 should be
between 100 and 220 pF.
Example:
• Vd d = 5V, Vt h = 3.0V, Vt l = 2.5V
• From Tip #3, R4 = 1k, R5 = 1.5k and R3 = 12k
• Tp u l s e = Im s , C1 = .1 mF and R2 = 15k
• D1 is a 1N4148, R1 = 220W and C2 = 150 pF
TIP #7 One-Shot
When dealing with short duration signals or
glitches, it is often convenient to stretch out the
event using a mono-stable, multi-vibrator or
one-shot. Whenever the input pulses, the
one-shot fires holding its output for a preset
period of time. This stretches the short
trigger input into a long output which the
microcontroller can capture.
The circuit is designed with two feedback paths
around a comparator. The first is a positive
hysteresis feedback which sets a two level
threshold, Vh i and Vl o , based on the state of
the comparator output. The second feedback
path is an RC time circuit.
The one-shot circuit presented in Figure 7-1 is
triggered by a low-high transition on its input
and generates a high output pulse. Using
the component values from the example, the
circuit’s operation is as follows.
Prior to triggering, C1 will have charged to
a voltage slightly above 0.7V due to resistor
R2 and D1 (R1 << R2 and will have only a
minimal effect on the voltage). The comparator
output will be low, holding the non-inverting
input slightly below 0.7V due to the hysteresis
feedback through R3, R4 and R5 (the hysteresis
lower limit is designed to be less than 0.7V).
With the non-inverting input held low, C2 will
charge up to the difference between the
circuit input and the voltage present at the
non-inverting input.
When the circuit input is pulsed high, the
voltage present at the non-inverting input is
pulled above 0.7V due to the charge in C2.
This causes the output of the comparator to go
high, the hysteresis voltage at the non-inverting
input goes to the high threshold voltage, and C1
begins charging through R2.
Tp u l s e = R2 * C1 * In(Vt h /vt l )
4
© 2009 Microchip Technology Inc. DS01146B-Page 4-9
PIC
®
Microcontroller Comparator Tips ‘n Tricks
To design a multi-vibrator, first design the
hysteresis feedback path using the procedure in
Tip #3. Be careful to choose threshold voltages
(Vt h and Vt l ) that are evenly spaced within the
common mode range of the comparator and
centered on Vd d /2. Then use Vd d and Vt l to
calculate values for RT and CT that will result in
the desired oscillation frequency Fo s c . Equation
8-1 defines the relationship between RT, CT,
Vt h , Vt l and Fo s c .
Equation 8-1
Example:
• Vd d = 5V, Vt h = 3.333, Vt l = 1.666V
• R1, to R2, to R3 = 10k
• Rt = 15 kHz, Ct = .1 mF for Fo s c = 480 Hz
TIP #8 Multi-Vibrator (Square Wave
Output)
A multi-vibrator is an oscillator designed around
a voltage comparator or operational amplifier
(see Figure 8-1). Resistors R1 through R3
form a hysteresis feedback path from the
output to the non-inverting input. Resistor RT
and capacitor CT form a time delay network
between the output and the inverting input. At
the start of the cycle, CT is discharged holding
the non-inverting input at ground, forcing
the output high. A high output forces the
non-inverting input to the high threshold voltage
(see Tip #3) and charges CT through RT.
When the voltage across CT reaches the high
threshold voltage, the output is forced low. A low
output drops the non-inverting input to the low
threshold voltage and discharges CT through
RT. When the voltage across CT reaches the
low threshold voltage, the output is forced high
and the cycle starts over.
Figure 8-1: Multi-Vibrator Circuit
Output
V
DD
+
-
RT
Comparator
R2
R3
CT
R1
Fo s c = 1
2 * RT * CT * In(V
t h
/V
t l
)
© 2009 Microchip Technology Inc.Page 4-10-DS01146B
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #9 Multi-Vibrator (Ramp Wave
Output)
A multi-vibrator (ramp wave output) is an
oscillator designed around a voltage comparator
or operational amplifier that produces an
asymmetrical output waveform (see Figure 9-1).
Resistors R1 through R3 form a hysteresis
feedback path from the output to the
non-inverting input. Resistor RT, diode D1 and
capacitor CT form a time delay network between
the output and the inverting input. At the start
of the cycle, CT is discharged holding the
non-inverting input at ground, forcing the output
high. A high output forces the non-inverting
input to the high threshold voltage (see Tip #3)
and charges CT through RT. When the voltage
across CT reaches the high threshold voltage,
the output is forced low. A low output drops the
non-inverting input to the low threshold voltage
and discharges CT through D1. Because
the dynamic on resistance of the diode is
significantly lower than RT, the discharge of CT
is small when compared to the charge time, and
the resulting waveform across CT is a pseudo
ramp function with a ramping charge phase and
a short-sharp discharge phase.
Figure 9-1: Ramp Waveform Multi-Vibrator
+
-
RT
Comparator
Output
R2
R3
CT
R1
V
DD
D1
To design this multi-vibrator, first design the
hysteresis feedback path using the procedure
in Tip #3. Remember that the peak-to-peak
amplitude of the ramp wave will be determined
by the hysteresis limits. Also, be careful to
choose threshold voltages (Vt h and Vt l ) that
are evenly spaced within the common mode
range of the comparator.
Then use Vt h and Vt l to calculate values for RT
and CT that will result in the desired oscillation
frequency Fo s c . Equation 9-1 defines the
relationship between RT, CT, Vt h , Vt l and Fo s c .
Equation 9-1
This assumes that the dynamic on resistance of
D1 is much less than RT.
Example:
• Vd d = 5V, Vt h = 1.666V and Vt h = 3.333V
• R1, R2 and R3 = 10k
• Rt = 15k, Ct = .1 mF for a Fo s c = 906 Hz
Note:
Replacing Rt with a current limiting
diode will significantly improve the
linearity of the ramp wave form.
Using the example shown above, a
CCL1000 (1 mA Central Semiconductor
CLD), will produce a very linear
6 kHz output (see Equation 9-2).
Equation 9-2
Figure 9-2: Alternate Ramp Waveform
Multi-Vibrator Using a CLD
CLD
+
-Comparator
Output
R2
R3
CT
R1
V
DD
D1
Fo s c = 1
RT * CT * In(V
t h
/V
t l
)
Fo s c = Ic l d
C (V
t h
- V
t l
)
© 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, first 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: Ro u t 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 modified for a Fo s c
of 4.8 kHz.
• C1 and C2 = 10 mF
• Ro u t = 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 flows from Vd d 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 Vd d . 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).
Ro u t = 1
F
s w i t c h
* 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.
© 2009 Microchip Technology Inc. DS01146B-Page 4-13
PIC
®
Microcontroller Comparator Tips ‘n Tricks
Once the gain has been determined, values for
R3 and C2 can be determined. R3 and C2 form
a low-pass filter on the output of the amplifier.
The corner frequency of the low pass should
be 2 to 3 times the maximum frequency of the
signal being amplified to prevent attenuation
of the signal, and R3 should be kept small to
minimize the output impedance of the amplifier.
Equation 12-2 shows the relationship between
R3, C2 and the corner frequency of the low
pass filter.
Equation 12-2
A value for C1 can then be determined using
Equation 12-3. The corner frequency should be
the same as Equation 12-3.
Equation 12-3
To design an inverting amp, choose resistors R1
and R2 using the Gain formula for an op amp
inverting amplifier (see Equation 12-4).
Equation 12-4
Then choose values for the resistor divider
formed by R4 and R5. Finally choose C1 and
C2 as shown in the non-inverting amplifier
design.
Example:
• For C2 will set the corner F
• Gain = 6.156, R1 = R3 = 19.8k
• R2 = 3.84k, C1 = .047 mF, Fc o r n e r = 171 Hz
• C2 = .22 mF
TIP #12 Making an Op Amp
Out of a Comparator
When interfacing to a sensor, some gain is
typically required to match the full range of the
sensor to the full range of an ADC. Usually this
is done with an operational amplifier, however,
in cost sensitive applications, an additional
active component may exceed the budget.
This tip shows how an on-chip comparator can
be used as an op amp like gain stage for slow
sensor signals. Both an inverting and
non-inverting topology are shown (see Figure
12-1 and Figure 12-2).
Figure 12-1: Non-Inverting Amplifier
Output
+
-
Comparator
C2
R3
R1
C1
R2
Input
Figure 12-2: Inverting Amplifier
VDD
10K
Output
+
-
Comparator
C2
R3
R1
C1
R2
Input
10K
To design a non-inverting amplifier, choose
resistors R1 and R2 using the Gain formula for
an op amp non-inverting amplifier (see Equation
12-1).
Equation 12-1
Gain = R1 + R2
R2
Fc o r n e r = 1
2 * W * R3 * C2
Fc o r n e r = 1
2 * W * (R1 II R2) * C2
Gain = R1
R2
© 2009 Microchip Technology Inc.Page 4-14-DS01146B
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #13 PWM High-Current Driver
This tip combines a comparator with a MOSFET
transistor and an inductor to create a switch mode
high-current driver circuit. (See Figure 13-1).
The operation of the circuit begins with the
MOSFET off and no current flowing in the
inductor and load. With the sense voltage across
R1 equal to zero and a DC voltage present at
the drive level input, the output of the comparator
goes low. The low output turns on the MOSFET
and a ramping current builds through the
MOSFET, inductor, load and R1.
Figure 13-1: High Current Driver
V
DD
Drive
Level
+
-
Comparator R3
R1
C1
R2
P ch
MOSFET
Load
When the current ramps high enough to generate
a voltage across R1 equal to the drive level, the
comparator output goes high turning off the
MOSFET. The voltage at the junction of the
MOSFET and the inductor then drops until D1
forward biases. The current continues ramping
down from its peak level toward zero. When the
voltage across the sense resistor R1 drops below
the drive level, the comparator output goes low,
the MOSFET turns on, and the cycle starts over.
R2 and C1 form a time delay network that limits
the switching speed of the driver and causes it
to slightly overshoot and undershoot the drive
level when operating. The limit is necessary to
keep the switching speed low, so the MOSFET
switches efficiently. If R2 and C1 were not
present, the system would run at a speed set
by the comparator propagation delay and the
switching speed of the MOSFET. At that speed,
the switching time of the MOSFET would be a
significant portion of the switching time and the
switching efficiency of the MOSFET would be too
low.
Figure 13-1: Current Through the Load
Time
Drive Level Ripple Current
Load Current
To design a PWM high current driver, first
determine a switching speed (Fs w x ) that is
appropriate for the system. Next, choose a
MOSFET and D1 capable of handling the load
current requirements. Then choose values for
R2 and C1 using Equation 13-1.
Equation 13-1
Next determine the maximum ripple current that
the load will tolerate, and calculate the required
inductance value for L1 using Equation 13-2.
Equation 13-2
Finally, choose a value for R1 that will produce
a feedback ripple voltage of 100 mV for the
maximum ripple current Ir i p p l e .
Example:
• Fs w x = 10 kHz, R2 = 22k, C1 = .01 mF
• Ir i p p l e = 100 mA, Vd d = 12V, Vl = 3.5V
• L = 4.25 mH
Fs w x = 2
R2 * C1
L = Vd d - Vl o a d
I
r i p p l e
* F
s w x
* 2
© 2009 Microchip Technology Inc. DS01146B-Page 4-15
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #14 Delta-Sigma ADC
This tip describes the creation of a hardware/
software-based Delta-Sigma ADC. A Delta-
Sigma ADC is based on a Delta-Sigma
modulator composed of an integrator, a
comparator, a clock sampler and a 1-bit DAC
output. In this example, the integrator is formed
by R1 and C1. The comparator is an on-chip
voltage comparator. The clock sampler is
implemented in software and the 1-bit DAC
output is a single I/O pin. The DAC output feeds
back into the integrator through R2.
Resistors R3 and R4 form a Vd d /2 reference for
the circuit (see Figure 14-1).
Figure 14-1: Delta-Sigma Modulator
+
-Comparator
R3
R1 R2
Input
C1
V
DD
R4
Software Data
In operation, the feedback output from the
software is a time sampled copy of the
comparator output. In normal operation, the
modulator output generates a PWM signal
which is inversely proportional to the input
voltage. As the input voltage increases,
the PWM signal will drop in duty cycle to
compensate. As the input decreases, the duty
cycle rises.
To perform an A-to-D conversion, the duty
cycle must be integrated over time, digitally, to
integrate the duty cycle to a binary value. The
software starts two counters. The first counts
the total number of samples in the conversion
and the second counts the number of samples
that were low. The ratio of the two counts is
equal to the ratio of the input voltage over Vd d .
Note: This assumes that R1 and R2 are
equal and R3 is equal to R4. If
R1 and R2 are not equal, then the
input voltage is also scaled by the
ratio of R2 over R1, and R3 must still
be equal to R4.
For a more complete description of the
operation of a Delta-Sigma ADC and example
firmware, see Application Note AN700 “Make A
Delta-Sigma Converter Using a Microcontroller’s
Analog Comparator Module.”
Example:
• R3 = R4 = 10 kHz
• R1 = R2 = 5.1k
• C1 = 1000 pF
© 2009 Microchip Technology Inc.Page 4-16-DS01146B
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #15 Level Shifter
This tip shows the use of the comparator as a
digital logic level shifter. The inverting input is
biased to the center of the input voltage range
(Vi n /2). The non-inverting input is then used for
the circuit input. When the input is below the
Vi n /2 threshold, the output is low. When the
input is above Vi n /2, then the output is high.
Values for R1 and R2 are not critical, though
their ratio should result in a threshold voltage
Vi n /2 at the mid-point of the input signal voltage
range. Some microcontrollers have the option to
connect the inverting input to an internal voltage
reference. To use the reference in place of R1
and R2, simply select the internal reference and
configure it for one half the input voltage range.
Note: Typical propagation delay for the
circuit is 250-350 ns using the typical
on-chip comparator peripheral of a
microcontroller.
Figure 15-1: Level Shifter
V
DD
A
+
-
Y
R1
R2
Example:
• Vi n = 0 - 2V, Vi n /2 = 1V, Vd d = 5V
• R2 = 10k, R3 = 3.9k
TIP #16 Logic: Inverter
When designing embedded control applications,
there is often the need for an external gate.
Using the comparator, several simple gates can
be implemented. This tip shows the use of the
comparator as an inverter.
The non-inverting input is biased to the center
of the input voltage range, typically Vd d /2. The
inverting input is then used for the circuit input.
When the input is below Vd d /2, the output is
high. When the input is above Vd d /2, then the
output is low.
Values for R1 and R2 are not critical, though
they must be equal to set the threshold at
Vd d /2.
Some microcontrollers have the option to
connect the inverting input to an internal voltage
reference. To use the reference in place of R1
and R2, move the input to the non-inverting
input and set the output polarity bit in the
comparator control register to invert the
comparator output.
Note: Typical propagation delay for the
circuit is 250-350 ns using the typical
on-chip comparator peripheral of a
microcontroller.
Figure 16-1: Inverter
V
DD
A
+
-
Y
R1
R2
© 2009 Microchip Technology Inc. DS01146B-Page 4-17
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #17 Logic: AND/NAND Gate
This tip shows the use of the comparator to
implement an AND gate and its complement
the NAND gate (see Figure 17-2). Resistors R1
and R2 drive the non-inverting input with 2/3 the
supply voltage. Resistors R3 and R4 average
the voltage of input A and B at the inverting
input. If either A or B is low, the average voltage
will be one half Vd d and the output of the
comparator remains low. The output will go
high only if both inputs A and B are high, which
raises the input to the inverting input above 2/3
Vd d .
The operation of the NAND gate is identical
to the AND gate, except that the output is
inverted due to the swap of the inverting and
non-inverting inputs.
Note:
Typical propagation delay for the
circuit is 250-350 ns using the typical
on-chip comparator peripheral of a
microcontroller. Delay measurements
were made with 10k resistance
values.
While the circuit is fairly simple, there are a few
requirements for correct operation:
1. The inputs A and B must drive from ground
to Vd d for the circuit to operate properly.
2. The combination of R1 and R2 will draw
current constantly, so they must be kept
large to minimize current draw.
3. All resistances on the inverting input react
with the input capacitance of the comparator.
So the speed of the gate will be affected by
the source resistance of A and B, as well as,
the size of resistors R3 and R4.
4. Resistor R2 must be 2 x R1.
5. Resistor R3 must be equal to R4.
Figure 17-1: AND Gate
VDD
A
+
-
Y
R2
R1
R4
R3
B
Figure 17-2: NAND Gate
VDD
A
+
-
Y
R2
R1
R4
R3
B
Example:
• Vd d = 5V, R3 = R4 = 10k
• R1 = 5.1k, R2 = 10k
© 2009 Microchip Technology Inc.Page 4-18-DS01146B
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #18 Logic: OR/NOR Gate
This tip shows the use of the comparator to
implement an OR gate, and its complement, the
NOR gate.
Resistors R1 and R2 drive the non-inverting
input of the comparator with 1/3 Vd d . Resistors
R3 and R4 average the voltages of the inputs
A and B at the inverting input. If either A or B
is high, the average voltage is 1/2 Vd d and the
output of the comparator is high. Only if both A
and B are low does the average voltage at the
non-inverting input drop below 1/3 the supply
voltage, causing the comparator output to go
low. The operation of the NOR gate is identical
to the OR gate, except the output is inverted
due to the swap of the inverting and
non-inverting inputs.
Note:
Typical propagation delay for the
circuit is 250-350 ns using the typical
on-chip comparator peripheral of a
microcontroller. Delay measurements
were made with 10k resistance
values.
While the circuit is fairly simple, there are a few
requirements for correct operation:
1. The inputs A and B must drive from ground to
Vd d for the circuit to operate properly.
2. The combination of R1 and R2 will draw
current constantly, so they must be kept large
to minimize current draw.
3. All resistances on the inverting input react
with the input capacitance of the comparator,
so the speed of the gate will be affected by
the source resistance of A and B, as well as
the size of resistors R3 and R4.
4. Resistor R1 must be 2 x R2.
5. Resistor R3 must be equal to R4.
Figure 18-1: OR Gate
VDD
A
+
-
Y
R2
R1
R4
R3
B
Figure 18-2: NOR Gate
VDD
A
+
-
Y
R2
R1
R4
R3
B
Example:
• Vd d = 5V, R3 = R4 = 10k
• R1 = 10k, R2 = 5.1k
© 2009 Microchip Technology Inc. DS01146B-Page 4-19
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #19 Logic: XOR/XNOR Gate
This tip shows the use of the comparator to
implement an XOR gate and its complement the
XNOR gate.
The operation is best described in three
sections:
1. Both A and B inputs are low
With both inputs low, the inverting input
is held at .7V and the non-inverting is held
at ground. This combination results in a low
output.
2. Both A and B inputs are high
With both inputs high, the inverting input is
pulled up to Vd d and the non-inverting input
is equal to 2/3 Vd d (the average of Vd d inputs
and Gn d ). This combination also results in a
low output.
3. Input A or B is high
With one input high and one low, The
inverting input is held at .7V and the
non-inverting input is equal to 1/3 Vd d (the
average of a Vd d input and Gn d ). This
combination results in a high output.
Note: Typical propagation delay for the
circuit is 250-350 ns using the typical
on-chip comparator peripheral of a
microcontroller. Delay measurements
were made with 10k resistance
values.
While the circuit is fairly simple, there are a few
requirements for correct operation:
1. The inputs A and B must drive from ground to
Vd d for the circuit to operate properly.
2. All resistances on the both inputs react with
the input capacitance of the comparator, so
the speed of the gate will be affected by the
source resistance of A and B, as well as, the
size of resistors R1, R2, R3 and R4.
3. Resistor R1, R2 and R3 must be equal.
4. Resistor R4 must be small enough to
produce a 1.0V, or lower, voltage drop across
D1 and D2.
Figure 19-1: XOR Gate
VDD
A
+
-
Y
R3
R4
R2
R1
B
D2
D1
Comparator
Figure 19-2: XNOR Gate
VDD
A
+
-
Y
R3
R4
R2
R1
B
D2
D1
Comparator
Example:
• D1 = D2, = 1N4148
• R4 = 10k, R1 = R2 = R3 = 5.1k
© 2009 Microchip Technology Inc.Page 4-20-DS01146B
PIC
®
Microcontroller Comparator Tips ‘n Tricks
TIP #20 Logic: Set/Reset Flip Flop
This tip shows the use of the comparator to
implement a Set/Reset Flip Flop.
The inverting and non-inverting inputs are
biases at Vd d /2 by resistors R1 through R4.
The non-inverting input also receives positive
feedback from the output through R5. The
common bias voltages and the positive
feedback configure the comparator as a bistable
latch. If the output Q is high, the non-inverting
input is also pulled high, which reinforces the
high output. If Q is low, the non-inverting input is
also pulled low, which reinforces the low output.
To change state, the appropriate input must be
pulled low to overcome the positive feedback.
The diodes prevent a positive state on either
input from pulling the bias of either input above
Vd d /2.
Note: Typical propagation delay for the
circuit is 250-350 ns using the typical
on-chip comparator peripheral of a
microcontroller. Delay measurements
were made with 10k resistance
values.
While the circuit is fairly simple, there are a few
requirements for correct operation:
1. The inputs Set and Reset must be driven
near ground for the circuit to operate
properly.
2. The combination of R1/R2 and R3/R4 will
draw current constantly, so they must be kept
large to minimize current draw.
3. R1 through R4 must be equal for a Vd d /2 trip
level.
4. R5 must be greater or equal to R3.
5. R1 through R4 will react with the input
capacitance of the comparator, so larger
values will limit the minimum input pulse
width.
Figure 20-1: Set/Reset Flip Flop
SET
R5
VDD
Q
R3
R4
VDD
R1
R2
+
-
RESET
Example:
• Diodes = 1N4148
• R1 = R2 = R3 = R4 = 10k
• R5 = 10k
© 2009 Microchip Technology Inc. DS01146B-Page 5-1
DC Motor Control Tips ‘n Tricks
Table Of Contents
TIPS ‘N TRICKS INTRODUCTION
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
TIPS ‘N TRICKS INTRODUCTION
Every motor control circuit can be divided
into the drive electronics and the controlling
software. These two pieces can be fairly simple
or extremely complicated depending upon
the motor type, the system requirements and
the hardware/software complexity trade-off.
Generally, higher performance systems require
more complicated hardware. This booklet
describes many basic circuits and software
building blocks commonly used to control
motors. The booklet also provides references
to Microchip application notes that describe
many motor control concepts in more detail. The
application notes can be found on the Microchip
web site at www.microchip.com.
Additional motor control design information can
be found at the Motor Control Design Center
(www.microchip.com/motor).
CHAPTER 5
DC Motor Control
Tips ‘n Tricks
© 2009 Microchip Technology Inc.Page 5-2-DS01146B
DC Motor Control Tips ‘n Tricks
Figure 1-3: H-Bridge Drive
A-D are digital outputs from a PIC® MCU.
V+
M
A
D
C
V+
B
The H-Bridge derived its name from the
common way the circuit is drawn. This is the
only solid state way to operate a motor in both
directions.
Application notes that drive Brushed DC motors
are listed below and can be found on the
Microchip web site at: www.microchip.com.
•AN847,“RC Model Aircraft Motor Control
(DS00847)
•AN893,“Low-cost Bidirectional Brushed DC
Motor Control Using the PIC16F684
(DS00893)
•AN905,“Brushed DC Motor Fundamentals
(DS00905)
TIP #1 Brushed DC Motor Drive
Circuits
All motors require drive circuitry which controls
thecurrentflowthroughthemotorwindings.
This includes the direction and magnitude of
thecurrentflow.Thesimplesttypeofmotor,to
drive, is the Brushed DC motor. Drive circuits for
this type of motor are shown below.
Figure 1-1: High Side Drive
MOSFET
Driver
V+
PIC®
Microcontroller
Digital
Output
M
This drive can control a Brushed DC motor in
one direction. This drive is often used in safety
critical applications because a short circuit at
the motor terminals cannot turn the motor on.
Figure 1-2: Low Side Drive
M
MOSFET
Driver
V+
PIC®
Microcontroller
Digital
Output
This is the lowest cost drive technique because
of the MOSFET drive simplicity. Most applications
can simply use an output pin from the PIC®
microcontroller to turn the MOSFET on.
© 2009 Microchip Technology Inc. DS01146B-Page 5-3
DC Motor Control Tips ‘n Tricks
TIP #2 Brushless DC Motor Drive
Circuits
A Brushless DC motor is a good example of
simplifiedhardwareincreasingthecontrol
complexity. The motor cannot commutate
thewindings(switchthecurrentflow),sothe
control circuit and software must control the
currentflowcorrectlytokeepthemotorturning
smoothly. The circuit is a simple half-bridge on
each of the three motor windings.
There are two basic commutation methods
for Brushless DC motors; sensored and
sensorless. Because it is critical to know the
position of the motor so the correct winding can
be energized, some method of detecting the
rotor position is required. A motor with sensors
will directly report the current position to the
controller. Driving a sensored motor requires
a look-up table. The current sensor position
directly correlates to a commutation pattern for
the bridge circuits.
Without sensors, another property of the
motormustbesensedtofindtheposition.A
popular method for sensorless applications
is to measure the back EMF voltage that is
naturally generated by the motor magnets and
windings. The induced voltage in the un-driven
winding can be sensed and used to determine
the current speed of the motor. Then, the next
commutation pattern can be determined by a
time delay from the previous pattern.
Sensorless motors are lower cost due to
the lack of the sensors, but they are more
complicated to drive. A sensorless motor
performs very well in applications that don’t
require the motor to start and stop. A sensor
motor would be a better choice in applications
that must periodically stop the motor.
Figure 2-1: 3 Phase Brushless DC Motor
Control
OA-OF are digital outputs from a PIC
®
MCU.
C
A
Motor
B
V
OA
OB
A
V
OC
OD
B
V
OE
OF
C
Figure 2-2: Back EMF Sensing (Sensorless
Motor)
PIC
®
MCU or dsPIC
®
DSC
ADC
Analog
MUX
Low Pass
Filter
A
B
C
© 2009 Microchip Technology Inc.Page 5-4-DS01146B
DC Motor Control Tips ‘n Tricks
Figure 2-3: Quadrature Decoder (Sensor Motor)
Digital
Outputs
A B C
PIC
®
MCU or dsPIC
®
DSC
Digital
Inputs
Hall
Effect
Motor
Position
Sensor
Drive
Circuit
Motor
Sensor
Outputs
Application notes describing Brushless DC Motor
Control are listed below and can be found on the
Microchip web site at: www.microchip.com.
•AN857,“Brushless DC Motor Control Made
Easy” (DS00857)
•AN885,“Brushless DC Motor Fundamentals
(DS00885)
•AN899,“Brushless DC Motor Control Using
PIC18FXX31” (DS00899)
•AN901,“Using the dsPIC30F for Sensorless
BLDC Control” (DS00901)
•AN957,“Sensored BLDC Motor Control Using
dsPIC30F2010” (DS00957)
•AN992,“Sensorless BLDC Motor Control
Using dsPIC30F2010” (DS00992)
•AN1017,“Sinusoidal Control of PMSM with
dsPIC30F DSC” (DS01017)
•GS005,“Using the dsPIC30F Sensorless
Motor Tuning Interface” (DS93005)
TIP #3 Stepper Motor Drive Circuits
Stepper motors are similar to Brushless
DC motors in that the control system must
commutate the motor through the entire rotation
cycle. Unlike the brushless motor, the position
and speed of a stepping motor is predictable
and does not require the use of sensors.
There are two basic types of stepper motors,
although some motors are built to be used in
either mode. The simplest stepper motor is
the unipolar motor. This motor has four drive
connections and one or two center tap wires
that are tied to ground or Vsupply, depending
on the implementation. Other motor types are
the bipolar stepper and various combinations
of unipolar and bipolar, as shown in Figure 3-1
and Figure 3-2. When each drive connection
is energized, one coil is driven and the motor
rotates one step. The process is repeated
until all the windings have been energized.
To increase the step rate, often the voltage is
increased beyond the motors rated voltage.
If the voltage is increased, some method of
preventing an over current situation is required.
There are many ways to control the winding
current, but the most popular is a chopper
system that turns off current when it reaches
anupperlimitandenablesthecurrentflowa
short time later. Current sensor systems are
discussed in Tip #6. Some systems are built
with a current chopper, but they do not detect
the current, rather the system is designed to
beginafixedperiodchoppingcycleafterthe
motor has stepped to the next position. These
are simpler systems to build, as they only
require a change in the software.
© 2009 Microchip Technology Inc. DS01146B-Page 5-5
DC Motor Control Tips ‘n Tricks
Figure 3-1: 4 and 5 Wire Stepper Motors
Unipolar 5 Wire Bipolar 4 Wire
Figure 3-2: 6 and 8 Wire Stepper Motors
Unipolar and Bipolar
6 Wire
Individual coils
wire anyway
appropriate
8 Wire
Short for
Unipolar
Figure 3-3: Unipolar Motor (4 Low Side
Switches)
01
V+
01-04 are outputs from a PIC
®
MCU or dsPIC
®
DSC.
Motor
02
04
03
Figure 3-4: Bipolar Motor (4 Half-Bridges)
A
-H are digital outputs from a PIC
®
MCU
or dsPIC
®
DSC.
V
A
B
C
D
V
Motor
V
E
F
G
H
V
© 2009 Microchip Technology Inc.Page 5-6-DS01146B
DC Motor Control Tips ‘n Tricks
TIP #4 Drive Software
Pulse-Width Modulation (PWM) Algorithms
Pulse-Width Modulation is critical to modern
digital motor controls. By adjusting the pulse
width,thespeedofamotorcanbeefficiently
controlled without larger linear power stages.
Some PIC devices and all dsPIC DSCs have
hardware PWM modules on them. These
modules are built into the Capture/Compare/
PWM (CCP) peripheral. CCP peripherals are
intended for a single PWM output, while the
Enhanced CCP (ECCP) is designed to produce
the complete H-Bridge output for bidirectional
Brushed DC motor control. If cost is a critical
design point, a PIC device with a CCP module
may not be available, so software generated
PWM is a good alternative.
The following algorithms are designed to
efficientlyproducean8-bitPWMoutputon
the Mid-Range family of PIC microcontrollers.
These algorithms are implemented as macros.
If you want these macros to be a subroutine
in your program, simply remove the macro
statements and replace them with a label and a
return statement.
Example 4-1: 1 Output 8-Bit PWM
pwm_counter equ xxx ;variable
pwm equ xxx ;variable
set_pwm macro A ;sets the pwm
;setpoint to the
;value A
MOVLW A
MOVWF pwm
endm
update_PWM macro ;performs one update
;of the PWM signal
;place the PWM output
;pin at bit 0 or 7 of
;the port
MOVF pwm_counter,w
SUBWF pwm, w ;if the output
;is on bit 0
RLF PORTC,f ;replace PORTC with
;the correct port if
;the output is on bit
;7 of the port
;replace the rlf with
;rrf incf
;pwm_counter,f
Example 4-2: 8 Output 8-Bit PWM
pwm_counter equ xxx ;variable
pwm0 equ xxx ;
pwm1 equ pwm0+1
pwm2 equ pwm1+1
pwm3 equ pwm2+1
pwm4 equ pwm3+1
pwm5 equ pwm4+1
pwm6 equ pwm5+1
pwm7 equ pwm6+1
output equ pwm7+1
set_pwm macro A,b ;sets pwm b with
;the value A
MOVLW pwm0
ADDLW b
MOVWF fsr
MOVLW a
MOVWF indf
endm
update_PWM macro ;peforms one
;update of all 8
;PWM signals
;all PWM signals
;must be on the
;same port
MOVF pwm_counter,w
SUBWF pwm0,w
RLF output,f
MOVF pwm_counter,w
SUBWF pwm1,w
RLF output,f
MOVF pwm_counter,w
SUBWF pwm2,w
RLF output,f
MOVF pwm_counter,w
SUBWF pwm3,w
RLF output,f
MOVF pwm_counter,w
SUBWF pwm4,w
RLF output,f
MOVF pwm_counter,w
SUBWF pwm5,w
RLF output,f
MOVF pwm_counter,w
SUBWF pwm6,w
RLF output,f
MOVF pwm_counter,w
SUBWF pwm7,w
RLF output,w
MOVWF PORTC
INCF pwm_counter,f
endm
© 2009 Microchip Technology Inc. DS01146B-Page 5-7
DC Motor Control Tips ‘n Tricks
TIP #5 Writing a PWM Value to the
the CCP Registers With a
Mid-Range PIC
®
Microcontroller
The two PWM LSb’s are located in the
CCPCON register of the CCP. This can make
changing the PWM period frustrating for a
developer. Example 5-1 through Example 5-3
show three macros written for the mid-range
product family that can be used to set the PWM
period.Thefirstmacrotakesa16-bitvalueand
uses the 10 MSb’s to set the PWM period. The
second macro takes a 16-bit value and uses the
10 LSb’s to set the PWM period. The last macro
takes 8 bits and sets the PWM period. This
assumesthattheCCPisconfiguredfornomore
than 8 bits.
Example 5-1: Left Justified 16-Bit Macro
pwm_tmp equ xxx ;this variable must be
;allocated someplace
setPeriod macro a ;a is 2 SFR’s in
;Low:High arrangement
;the 10 MSb’s are the
;desired PWM value
RRF a,w ;This macro will
;change w
MOVWF pwm_tmp
RRF pwm_tmp,w
ANDLW 0x30
IORLW 0x0F
MOVWF CCP1CON
MOVF a+1,w
MOVWF CCPR1L
Example 5-2: Right Justified 16-Bit Macro
pwm_tmp equ xxx ;this variable must be
;allocated someplace
setPeriod macro a ;a is 2 bytes in
;Low:High arrangement
;the 10 LSb’s are the
;desired PWM value
SWAPF a,w ;This macro will
;change w
ANDLW 0x30
IORLW 0x0F
MOVWF CCP1CON
RLF a,w
IORLW 0x0F
MOVWF pwm_tmp
RRF pwm_tmp,f
RRF pwm_tmp,w
MOVWF CCPR1L
Example 5-3: 8-Bit Macro
pwm_tmp equ xxx ;this variable must be
;allocated someplace
setPeriod macro a ;a is 1 SFR
SWAPF a,w ;This macro will
;change w
ANDLW 0x30
IORLW 0x0F
MOVWF CCP1CON
RRF a,w
MOVWF pwm_tmp
RRF pwm_tmp,w
MOVWF CCPR1L
© 2009 Microchip Technology Inc.Page 5-8-DS01146B
DC Motor Control Tips ‘n Tricks
Figure 6-2: Resistive Low Side Current
Sensing
ADC
CCP
Current Sensor
Amplifier
Current
Sensor
Resistor
VSUPPLY
M
PIC
®
MCU
or
dsPIC
®
DSC
MOSFET
Driver
MCP
 
+
-
Current measurement can also be
accomplished using a Hall effect sensor to
measurethemagneticfieldsurroundinga
current carrying wire. Naturally, this Hall effect
sensor can be located on the high side or the
low side of the load. The actual location of the
sensor does not matter because the sensor
does not rely upon the voltage on the wire. This
is a non-intrusive method that can be used to
measure motor current.
Figure 6-3: Magnetic Current Sensing
CCP
PIC
®
MCU
or
dsPIC
®
DSC
ADC
Hall
Effect
Sensor
Ferrite
Toroid
Motor Supply
M
V
DD
TIP #6 Current Sensing
The torque of an electric motor can be
monitored and controlled by keeping track of
thecurrentflowingthroughthemotor.Torque
is directly proportional to the current. Current
can be sensed by measuring the voltage drop
through a known value resistor or by measuring
themagneticfieldstrengthofaknownvalue
inductor. Current is generally sensed at one of
two places, the supply side of the drive circuit
(high side current sense) or the sink side of the
drive circuit (low side current sense). Low side
sensing is much simpler but the motor will no
longer be grounded, causing a safety issue in
some applications. High side current sensing
generallyrequiresadifferentialamplifierwitha
common mode voltage range within the voltage
of the supply.
Figure 6-1: Resistive High Side Current
Sensing
Current Sensor
Resistor
V
SUPPLY
M
PIC
®
MCU
or
dsPIC
®
DSC
ADC
RS-
MOSFET
Driver
CCP
RS+
V+
1k
MAX4172
High Side
Current
Sensor
Amplifier
© 2009 Microchip Technology Inc. DS01146B-Page 5-9
DC Motor Control Tips ‘n Tricks
Rotary Encoder Sensing
Rotary encoders are typically used to provide
direct physical feedback of motor position,
and/or speed. A rotary encoder consists of a
rotary element attached to the motor that has
a physical feature, measured by a stationary
component. The measurements can yield motor
speed and sometimes they can provide a motor
position. Rotary encoders are built using many
different technologies. The most common type
is an optical rotary encoder. The optical rotary
encoder is used in the computer mice that have
a ball. It is built with an encoder disc that is
attached to the motor. The encoder disc has
manyradialslotscutintothediscataspecific
interval. An LED and a photo detector are used
to count the slots as they go by. By timing the
rate that the slots go by, the speed of rotation
can be determined.
Sensing motor position requires a second LED
and photo detector. The second sensor pair
is mounted so the output pulses are 90° out
ofphasefromthefirstpair.Thetwooutputs
represent the motion of the encoder disc as a
quadrature modulated pulse train. By adding
a third index signal, that pulses once for each
revolution, the exact position of the rotor can be
known.
An encoder with quadrature outputs can be
used to track relative position from a known
reference point. Another type of encoder uses
a binary encoded disk so that the exact rotor
position is always known. This type of encoder
is called an absolute encoder.
TIP #7 Position/Speed Sensing
The motor RPM can be measured by
understanding that a motor is a generator. As
long as the motor is spinning, it will produce
a voltage that is proportional to the motors
RPM. This is called back EMF. If the PWM
signal to the motor is turned off and the voltage
across the windings is measured, the back
EMF voltage can be sensed from there and the
RPM’s can be known.
Figure 7-1: Back EMF Motor Speed Sensing
Q1
CCP
M
PIC
®
MCU
or
dsPIC
®
DSC
ADC
Motor Supply
V
DD
Back EMF Monitor
(1)
Note 1: If motor voltage is greater than V
DD
, an
attenuator will be required. Sample back
EMF while Q1 is off.
© 2009 Microchip Technology Inc.Page 5-10-DS01146B
DC Motor Control Tips ‘n Tricks
Figure 7-2: Optical Speed/Direction/Position
Sensing
Note: Frequency of one signal provides RPM of motor. Pulse count
provides motor position. A-B phase provides motor direction.
Encoder Wheel
A
B
M
Drive
Encoder Wheel
on Motor Shaft
V
DD
PIC
®
MCU
or
dsPIC
®
DSC
A
V
DD
B
A
B forward
B reverse
Photo
Transistor
LED
Quadrature sensing can easily be accomplished
in software, but there is generally an upper limit
to the RPM. By using a few gates, the sensing
can be done partially in hardware and partially
in software. The new PIC18FXX31 and dsPIC
16-bit Digital Signal Controller families include
an encoder interface that allows MUCH higher
RPM motors to be measured with an excellent
degree of accuracy.
Older Methods of Motor Sensing
Resolvers and analog tachometers are two
older technologies for motor position/velocity
sensing. An analog tachometer is simply an
electric generator with a linear output over
aspecifiedrangeofRPM’s.Byknowingthe
output characteristics, the RPM can be known
by simply measuring the voltage across the
tachometer terminals.
A resolver is a pair of coils that are excited
by an external AC signal. The two coils are
at 90° to each other so they pick up the AC
signal at different strengths, depending on
their orientation. The result is a sine or cosine
output related to the angle of the resolver in
reference to the AC signal. Inverse cosine/sine
will produce the angle of the sensor. This type
of sensor can be very accurate and is still used
where absolute position must be known.
© 2009 Microchip Technology Inc. DS01146B-Page 5-11
DC Motor Control Tips ‘n Tricks
Motor Control Development Tools
•PICDEM™MCDevelopmentBoard
(DM183011)
Used to evaluate the PIC18FXX31 8-bit
microcontroller family.
•PICDEM™MCLVDevelopmentBoard
(DM183021)
•dsPIC30FMotorControlDevelopmentSystem
(DM300020)
Used to evaluate the dsPIC30F 16-bit Digital
Signal Controller family.
•MotorControl(MC)GraphicalUserInterface
(GUI)
 TheMC-GUIallowsusertoconfigurethe
motor and a wide range of system parameters
for a selected motor type.
The MC-GUI is free an can be downloaded at
www.microchip.com
Visit the Motor Control Design Center at:
www.microchip.com/motor for additional
design resources.
Application Note References
•AN532,“Servo Control of a DC Brush Motor
(DS00532)
•AN696,“PIC18CXXX/PIC16CXXX DC
Servomotor” (DS00696)
•AN718,“Brush-DC Servomotor
Implementation using PIC17C756A
(DS00718)
•AN822,“Stepper Motor Microstepping with the
PIC18C452” (DS00822)
•AN843,“Speed Control of 3-Phase Induction
Motor Using PIC18 Microcontrollers
(DS00843)
•AN847,“RC Model Aircraft Motor Control
(DS00847)
•AN857,“Brushless DC Motor Control Made
Easy” (DS00857)
•AN885,“Brushless DC (BLDC) Motor
Fundamentals” (DS00885)
•AN899,“Brushless DC Motor Control Using
the PIC18FXX31” (DS00899)
•AN893,“Low-cost Bidirectional Brushed
DC Motor Control Using the PIC16F684
(DS00893)
•AN894,“Motor Control Sensor Feedback
Circuits” (DS00894)
•AN898,“Determining MOSFET Driver Needs
for Motor Drive Applications” (DS00898)
•AN901,“Using the dsPIC30F for Sensorless
BLDC Control” (DS00901)
•AN905,“Brushed DC Motor Fundamentals
(DS00905)
•AN906,“Stepper Motor Control Using the
PIC16F684” (DS00906)
•AN907,“Stepper Motor Fundamentals
(DS00907)
•AN1017,“Sinusoidal Control of PMSM Motors
with dsPIC30F DSC” (DS01017)
•GS001,“Getting Started with BLDC Motors
and dsPIC30F Devices” (DS93001)
Application notes can be found on the Microchip
web site at www.microchip.com.
© 2009 Microchip Technology Inc.Page 5-12-DS01146B
DC Motor Control Tips ‘n Tricks
NOTES:
© 2009 Microchip Technology Inc. DS01146B-Page 6-1
LCD PIC
®
Microcontroller Tips ‘n Tricks
Table Of Contents
TIPS ‘N TRICKS INTRODUCTION
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
TIPS ‘N TRICKS INTRODUCTION
Using an LCD PIC® MCU for any embedded
application can provide the benefits of system
control and human interface via an LCD. Design
practices for LCD applications can be further
enhanced through the implementation of these
suggested “Tips ‘n Tricks”.
This booklet describes many basic circuits and
software building blocks commonly used for
driving LCD displays. The booklet also provides
references to Microchip application notes that
describe many LCD concepts in more detail.
CHAPTER 6
LCD PIC® Microcontroller
Tips ‘n Tricks
© 2009 Microchip Technology Inc.Page 6-2-DS01146B
LCD PIC
®
Microcontroller Tips ‘n Tricks
6. Request a minimal initial prototype LCD build
to ensure proper LCD development and
ensure proper functionality within the target
application.
a) Allow typically 4-6 weeks for initial LCD
prototype delivery upon final approval of
mechanical drawings and pin
assignments.
7. Upon receipt of prototype LCD, confirm
functionality before giving final approval and
beginning production of LCD.
Note: Be sure to maintain good records by
keeping copies of all materials
transferred between both parties,
such as initial sketches, drawings,
pinouts, etc.
TIP #2 LCD PIC
®
MCU Segment/
Pixel Table
Table 2-1: Segment Matrix Table
Multiplex
Commons
Maximum Number of Segments/Pixels
Bias
PIC16F913/
916
PIC16F914/
917 PIC16F946 PIC18F6X90
(PIC18F6XJ90)
PIC18F8X90
(PIC18F8XJ90)
Static
(COM0)
15 24 42 32/
(33)
48 Static
1/2 (COM1:
COM0)
30 48 84 64/
(66)
96 1/2 or
1/3
1/3 (COM2:
COM0)
45 72 126 96/
(99)
144 1/2 or
1/3
1/4 (COM3:
COM0)
60 96 168 128/
(132)
192 1/3
This Segment Matrix table shows that
Microchip’s 80-pin LCD devices can drive up
to 4 commons and 48 segments (192 pixels),
64-pin devices can drive up to 33 segments
(132 pixels), 40/44 pin devices can drive up to
24 segments (96 pixels) and 28-pin devices can
drive 15 segments (60 segments).
TIP #1 Typical Ordering
Considerations and Procedures
for Custom Liquid Displays
1. Consider what useful information needs to
be displayed on the custom LCD and the
combination of alphanumeric and custom
icons that will be necessary.
2. Understand the environment in which the
LCD will be required to operate. Operating
voltage and temperature can heavily
influence the contrast of the LCD and
potentially limit the type of LCD that can be
used.
3. Determine the number of segments
necessary to achieve the desired
display on the LCD and reference the
PIC Microcontroller LCD matrix for the
appropriate LCD PIC microcontroller.
4. Create a sketch/mechanical print and
written description of the custom LCD
and understand the pinout of the LCD.
(Pinout definition is best left to the glass
manufacturer due to the constraints of
routing the common and segment electrodes
in two dimensions.)
5. Send the proposed LCD sketch and
description for a written quotation to at least
3 vendors to determine pricing, scheduling
and quality concerns.
a) Take into account total NRE cost, price
per unit, as well as any setup fees.
b) Allow a minimum of two weeks for formal
mechanical drawings and pin assignments
and revised counter drawings.
© 2009 Microchip Technology Inc. DS01146B-Page 6-3
LCD PIC
®
Microcontroller Tips ‘n Tricks
TIP #3 Resistor Ladder for Low
Current
Bias voltages are generated by using an
external resistor ladder. Since the resistor
ladder is connected between Vd d and Vs s ,
there will be current flow through the resistor
ladder in inverse proportion to the resistance. In
other words, the higher the resistance, the less
current will flow through the resistor ladder. If
we use 10K resistors and Vd d = 5V, the resistor
ladder will continuously draw 166 mA. That
is a lot of current for some battery-powered
applications.
Figure 3-1: Resistor Ladder
LCD PIC® MCU
COMm
V
DD
R
C
PIXEL
(n x m)
V
SS
V
LCD
3
V
LCD2
V
LCD1
V
LCD
0
SEGn
R
R
How do we maximize the resistance without
adversely effecting the quality of the display?
Some basic circuit analysis helps us determine
how much we can increase the size of the
resistors in the ladder.
The LCD module is basically an analog
multiplexer that alternately connects the LCD
voltages to the various segment and common
pins that connect across the LCD pixels. The
LCD pixels can be modeled as a capacitor.
Each tap point on the resistor ladder can be
modeled as a Thevenin equivalent circuit. The
Thevenin resistance is 0 for Vl c d 3 and Vl c d 0,
so we look at the two cases where it is non-
zero, Vl c d 2 and Vl c d 1.
The circuit can be simplified as shown in Figure
3-2. Rs w is the resistance of the segment
multiplex switch; Rc o m is the resistance of the
common multiplex switch.
Figure 3-2: Simplified LCD Circuit
CPIXEL
+
-
RTH RSW
RCOM
VTH
The Thevenin voltage is equal to either 2/3 Vd d ,
or 1/3 Vd d , for the cases where the Thevenin
resistance is non-zero. The Thevenin resistance
is equal to the parallel resistance of the upper
and lower parts of the resistor ladder.
Figure 3-3: LCD Circuit Resistance Estimate
C
PIXEL
+
-
V
TH
R
TOTAL
= R
TH
+ R
SW
+ R
COM
R
TH
= (2R * R)/(2R + R)
R
TH
= 2R2/3R
R
TH
= 2R/3
R
SW
= 4.7K
R
COM
= 0.4K
As you can see, we can model the drive of a
single pixel as an RC circuit, where the voltage
switches from 0V to Vl c d 2, for example. For
LCD PIC microcontrollers, we can estimate the
resistance of the segment and common
switching circuits as about 4.7K and 0.4K,
respectively.
We can see that the time for the voltage
across the pixel to change from 0 to Vt h will
depend on the capacitance of the pixel and the
total resistance, of which the resistor ladder
Thevenin resistance forms the most significant
part.
© 2009 Microchip Technology Inc.Page 6-4-DS01146B
LCD PIC
®
Microcontroller Tips ‘n Tricks
We want the time constant to be much smaller
than the period of the LCD waveform, so that
rounding of the LCD waveform will be minimized.
If we want the RC to be equal to 100 mS, then
the total resistance can be calculated as shown:
Equation 3-3
The resistance of the switching circuits within
the LCD module is very small compared to
this resistance, so the Thevenin resistance
of the resistor ladder at Vl c d 2 and Vl c d 1 can
be treated the same as Rt o t a l . We can then
calculate the value for R that will give us the
correct Thevenin resistance.
Equation 3-4
Now we can calculate the current through the
resistor ladder if we used 3.3 mΩ resistors.
Equation 3-5
Use this process to estimate maximum resistor
sizes for your resistor ladder and you will
drastically reduce power consumption for your
LCD application. Don’t forget to observe the
display over the operating conditions of your
product (such as temperature, voltage and
even, humidity) to ensure that contrast and
display quality is good.
Figure 3-4: Voltage Change Across Pixel
CPIXEL
+
-
VTH
RTOTAL
VPIXEL
The step response of the voltage across a pixel
is subject to the following equation:
Equation 3-1
By manipulating the equation, we can see that it
will take a time equal to 4 time constants for the
pixel voltage to reach 98% of the bias voltage.
Figure 3-5: Step Response Diagram
0
VPIXEL/VTH = 1 - e -
t
/RC
98% = 1 - e -
t
/RC
2% = e -
t
/RC
In (.02) = -t/RC
t = ~ 4 RC
t
VTH
0.98 VTH
VPIXEL
t = 4 RC
Now we need to estimate the capacitance.
Capacitance is proportional to the area of a
pixel. We can measure the area of a pixel and
estimate the capacitance as shown. Obviously,
a bigger display, such as a digital wall clock, will
have bigger pixels and higher capacitance.
Equation 3-2
Vp i x e l = Vt h (1 - e-t/r c )
Cp i x e l = 1500 pF/cm2
AREAp i x e l = 1 mm * 3 mm = .03 cm2
Cp i x e l = 45 pF
Rt o t a l = 100 mS/45 pF = 2.22 mΩ
Rt h = 2.2M - 5.1K = 2.2M
R = 3 Rt h /2 = 3.3M
Rl a d d e r = 9.9M,
Il a d d e r = 5V/9.9M = 0.5 mA
© 2009 Microchip Technology Inc. DS01146B-Page 6-5
LCD PIC
®
Microcontroller Tips ‘n Tricks
TIP #4: Contrast Control with a
Buck Regulator
Contrast control in any of the LCD PIC MCUs is
accomplished by controlling the voltages applied
to the Vl c d voltage inputs. The simplest contrast
voltage generator is to place a resistor divider
across the three pins. This circuit is shown in
the data sheet. The resistor ladder method is
good for many applications, but the resistor
ladder does not work in an application where the
contrast must remain constant over a range of
Vd d s . The solution is to use a voltage regulator.
The voltage regulator can be external to the
device, or it can be built using a comparator
internal to the LCD PIC microcontroller.
Figure 4-1: Voltage Generator with
Resistor Divider
LCD
Glass
PIC16F91X
R1
VLCD
1
RA1
R3
R2
R6
C3
C2
R5
R4
0.6V
VDD
VLCD
3
VLCD
2
RA5
C1
The PIC16F946/917/916/914/913 devices have
a special Comparator mode that provides a
fixed 0.6V reference. The circuit shown in Figure
4-1 makes use of this reference to provide a
regulated contrast voltage. In this circuit, R1, R2
and R3 provide the contrast control voltages.
The voltage on Vl c d 3 is compared to the internal
voltage reference by dividing the voltage at
Vl c d 3 at R4 and R5 and applying the reduced
voltage to the internal comparator. When the
voltage at Vl c d 3 is close to the desired voltage,
the output of the comparator will begin to
oscillate. The oscillations are filtered into a DC
voltage by R6 and C1. C2 and C3 are simply
small bypass capacitors to ensure that the
voltages at Vl c d 1 and Vl c d 2 are steady.
TIP #5: Contrast Control Using a
Boost Regulator
In LCD Tip #4, a buck converter was created
using a comparator. This circuit works great
when Vd d is greater than the LCD voltage. The
PIC microcontroller can operate all the way
down to 2.0V, whereas most low-voltage LCD
glass only operates down to 3V. In a battery
application, it is important to stay operational as
long as possible. Therefore, a boost converter is
required to boost 2.0V up to 3.0V for the LCD.
The figure below shows one circuit for doing
this.
Figure 5-1: Boost Converter
D1
C1
PIC16F946/917/916/914/913
R6
R3
R7
R1
R5
C1
V
DD
D3
C2
D2
Q1
R4
R2
C2
Boost
In this circuit, both comparators are used. The
voltage setpoint is determined by the value of
Zenier diode D3 and the voltage at R6:R7. The
rest of the circuit creates a simple multivibrator
to stimulate a boost circuit. The boost circuit
can be inductor or capacitor-based. When
the output voltage is too low, the multivibrator
oscillates and causes charge to build up in C2.
As the voltage at C2 increases, the multivibrator
will begin to operate sporadically to maintain the
desired voltage at C2.
© 2009 Microchip Technology Inc.Page 6-6-DS01146B
LCD PIC
®
Microcontroller Tips ‘n Tricks
TIP #6: Software Controlled Contrast
with PWM for LCD Contrast
Control
In the previous contrast control circuits, the
voltage output was set by a fixed reference. In
some cases, the contrast must be variable to
account for different operating conditions. The
CCP module, available in the LCD controller
devices, allows a PWM signal to be used for
contrast control. In Figure 6-1, you see the
buck contrast circuit modified by connecting
the input to RA6 to a CCP pin. The resistor
divider created by R4 and R5 in the previous
design are no longer required. An input to the
ADC is used to provide feedback but this can
be considered optional. If the ADC feedback
is used, notice that it is used to monitor the
Vd d supply. The PWM will then be used to
compensate for variations in the supply voltage.
Figure 6-1: Software Controlled Voltage
Generator
LCD
Glass
LCD PIC®
MCU
R1
VLCD
1
AN0
R3
R2
R6
C3
C2
R5
VDD
VLCD
3
VLCD
2
CCP
C1
VDD
D1
Figure 5-2: Two Types of Boost Converter
L1
VBAT
VBAT
Q2
R8
The two methods of producing a boost
converter are shown above. The first circuit is
simply a switched capacitor type circuit. The
second circuit is a standard inductor boost
circuit. These circuits work by raising Vd d . This
allows the voltage at Vl c d to exceed Vd d .
© 2009 Microchip Technology Inc. DS01146B-Page 6-7
LCD PIC
®
Microcontroller Tips ‘n Tricks
TIP #7 Driving Common Backlights
Any application that operates in a low light
condition requires a backlight. Most low-cost
applications use one of the following backlights:
1) Electroluminescent (EL)
2) LEDs in series
3) LEDs in parallel
Other backlight technologies, such as CCFL,
are more commonly used in high brightness
graphical panels, such as those found in laptop
computers. The use of white LEDs is also more
common in color LCDs, where a white light
source is required to generate the colors.
Driving an EL panel simply requires an AC
signal. You may be able to generate this signal
simply by using an unused segment on the LCD
controller. The signal can also be generated
by a CCP module or through software. The AC
signal will need to pass through a transformer
for voltage gain to generate the required voltage
across the panel.
LEDs in series can be easily driven with a boost
power supply. In the following diagram, a simple
boost supply is shown. In this circuit, a pulse
is applied to the transistor. The pulse duration
is controlled by current through R2. When the
pulse is turned off, the current stored in the
inductor will be transferred to the LEDs. The
voltage will rise to the level required to drive
the current through the LEDs. The breakdown
voltage of the transistor must be equal to the
forward voltage of the LEDs multiplied by the
number of LEDs. The comparator voltage
reference can be adjusted in software to change
the output level of the LEDs.
Figure 7-1: Simple Boost Supply
L1
VDD
Q2
R1
R2
LED String
To Comparator Input
If the LEDs are in parallel, the drive is much
simpler. In this case, a single transistor can be
used to sink the current of many LEDs in
parallel. The transistor can be modulated by
PWM to achieve the desired output level. If Vd d
is higher than the maximum forward voltage, a
resistor can be added to control the current, or
the transistor PWM duty cycle can be adjusted
to assure the LEDs are operating within their
specification.
Figure 7-2: LEDs in Parallel
R1
VDD
LED
String
© 2009 Microchip Technology Inc.Page 6-8-DS01146B
LCD PIC
®
Microcontroller Tips ‘n Tricks
TIP #9 LCD in Sleep Mode
If you have a power-sensitive application that
must display data continuously, the LCD PIC
microcontroller can be put to Sleep while the
LCD driver module continues to drive the
display.
To operate the LCD in Sleep, only two steps
are required. First, a time source other than the
main oscillator must be selected as the LCD
clock source, because during Sleep, the main
oscillator is Halted. Options are shown for the
various LCD PIC MCUs.
Table 9-1: Options for LCD in Sleep Mode
Part LCD Clock Source Use in
Sleep?
PIC16C925/926
Fo s c /256 No
T1OSC Yes
Internal RC Oscillator Yes
PIC16F946/917/
916/914/913
Fo s c /8192 No
T1OSC/32 Yes
LFINTOSC/32 Yes
PIC18F6X90 (Fo s c /4)/8192 No
PIC18F8X90 T1OSC Yes
PIC18F6XJ90 INTRC/32 Yes
PIC18F8XJ90
Second, the Sleep Enable bit (SLPEN) must be
cleared. The LCD will then continue to display
data while the part is in Sleep. It’s that easy!
When should you select the internal RC
oscillator (or LFINTOSC) over the Timer1
oscillator? It depends on whether your
application is time-sensitive enough to require
the accuracy of a crystal on the Timer1 oscillator
or not. If you have a timekeeping application,
then you will probably have a 32 kHz crystal
oscillator connected to Timer1.
Since Timer1 continues to operate during
Sleep, there is no penalty in using Timer1 as the
LCD clock source. If you don’t need to use an
external oscillator on Timer1, then the internal
RC oscillator (INTRC or LFINTOSC) is more
than sufficient to use as the clock source for the
LCD and it requires no external components.
TIP #8 In-Circuit Debug (ICD)
There are two potential issues with using the
ICD to debug LCD applications. First, the LCD
controller can freeze while the device is Halted.
Second, the ICD pins are shared with segments
on the PIC16F946/917/916/914/913 MCUs.
When debugging, the device is Halted at
breakpoints and by the user pressing the
pause button. If the ICD is configured to Halt
the peripherals with the device, the LCD
controller will Halt and apply DC voltages to
the LCD glass. Over time, these DC levels
can cause damage to the glass; however, for
most debugging situations, this will not be a
consideration. The PIC18F LCD MCUs have a
feature that allows the LCD module to continue
operating while the device has been Halted
during debugging. This is useful for checking
the image of the display while the device is
Halted and for preventing glass damage if the
device will be Halted for a long period of time.
The PIC16F946/917/916/914/913 multiplex the
ICSP™ and ICD pins onto pins shared with
LCD segments 6 and 7. If an LCD is attached
to these pins, the device can be debugged with
ICD; however, all the segments driven by those
two pins will flicker and be uncontrolled. As
soon as debugging is finished and the device is
programmed with Debug mode disabled, these
segments will be controlled correctly.
© 2009 Microchip Technology Inc. DS01146B-Page 6-9
LCD PIC
®
Microcontroller Tips ‘n Tricks
TIP #11 Blinking LCD
Information can be displayed in more than one
way with an LCD panel. For example, how can
the user’s attention be drawn to a particular
portion of the LCD panel? One way that does
not require any additional segments is to create
a blinking effect.
Look at a common clock application. The “:”
between the hours and minutes is commonly
made to blink once a second (on for half a
second, off for half a second). This shows that
the clock is counting in absence of the ticking
sound or second hand that accompanies the
usual analog face clock. It serves an important
purpose of letting the user know that the clock is
operating.
If there is a power outage, then it is common for
the entire clock display to blink. This gives the
user of the clock an immediate indication that
the clock is no longer showing the correct time.
When the user sets the time, then blinking is
commonly used to show that a new mode has
been entered, such as blinking the hours to
identify that the hours are being set, or blinking
the minutes to show that the minutes are
being set. In a simple clock, blinking is used
for several different purposes. Without blinking
effects, the common digital clock would not be
nearly as user friendly.
TIP #10 How to Update LCD
Data Through Firmware
To update the LCD, the content of the LCDDATA
registers is modified to turn on, or off, each pixel
on the LCD display. The application firmware
will usually modify buffer variables that are
created to correspond with elements on the
display, such as character positions, bar graph,
battery display, etc.
When the application calls for a display update,
the values stored in the buffer variables must be
converted to the correct setting of the pixel bits,
located in the LCDDATA registers.
For Type-A waveforms, the LCD Data registers
may be written any time without ill effect.
However, for Type-B waveforms, the LCD Data
registers can only be written every other LCD
frame in order to ensure that the two frames of
the Type-B waveform are compliments of one
another. Otherwise, a DC bias can be presented
to the LCD.
The LCD Data registers should only be written
when a write is allowed, which is indicated by
the WA bit in the LCDCON register being set.
On the PIC16C926 parts, there is no WA bit.
The writing of the pixel data can be coordinated
on an LCD interrupt. The LCD interrupt is only
generated when a multiplexed (not static)
Type-B waveform is selected.
© 2009 Microchip Technology Inc.Page 6-10-DS01146B
LCD PIC
®
Microcontroller Tips ‘n Tricks
TIP #12 4 x 4 Keypad Interface that
Conserves Pins for LCD
Segment Drivers
A typical digital interface to a 4 x 4 keypad uses
8 digital I/O pins. But using eight pins as digital
I/Os can take away from the number of segment
driver pins available to interface to an LCD.
By using 2 digital I/O pins and 2 analog input
pins, it is possible to add a 4 x 4 keypad to the
PIC microcontroller without sacrificing any of its
LCD segment driver pins.
The schematic for keypad hook-up is shown
in Figure 12-1. This example uses the
PIC18F8490, but the technique could be used
on any of the LCD PIC MCUs.
Figure 12-1: Keypad Hook-up Schematic
Figure 11-1: Common Clock Application
Fortunately, blinking is quite easy to implement.
There are many ways to implement a blinking
effect in software. Any regular event can be
used to update a blink period counter. A blink
flag can be toggled each time the blink period
elapses. Each character or display element
that you want to blink can be assigned a
corresponding blink enable flag. The flowchart
for updating the display would look like:
Figure 11-2: Updating Display Flowchart
N
N
YY
Character 1
Blink
Enable
Blink Flag
Start
Finish
Is Blink
flag
set?
Update
Character 1
Pixels
Clear
Character 1
Pixels
Is
Character 1
Blink enable
set?
LCDDATA
Pixel Bits
Update Character 1
Character 1
Buffer
© 2009 Microchip Technology Inc. DS01146B-Page 6-11
LCD PIC
®
Microcontroller Tips ‘n Tricks
8. Finally, check each value against the
matching column of Table 12-1. If it is within
±10% of a value, then it can be taken to
indicate that the corresponding key has been
pressed.
Table 12-1: Keypad Values
Value
±10% RB0_AN0 RB0_AN1 RB5_AN0 RB5_AN1
<Vd d /10 – – – –
Vd d /5.2 2 8 C E
Vd d /4.2 1 7 3 9
Vd d /3 5 0 D F
Vd d /2 4 A 6 B
9. This loop should be repeated about once
every 20 ms or so.
Don’t forget a debounce routine. For example,
require the above steps (with 20 ms delay
between) to return the same key value twice
in a row for that key to be considered pressed.
Also, require a no key press to be returned at
least twice before looking for the next key press.
When keys within the same quadrant are
pressed simultaneously, voltages other than
the four valid levels shown in the table may be
generated. These levels can either be ignored,
or if you want to use simultaneous key presses
to enable certain functions, you can add
decoding for those levels as well.
The two digital I/O pins that are used are RB0
and RB5, but any two digital I/O pins could
work. The two analog pins used are AN0 and
AN1.
To read the keypad, follow the steps below:
1. First, make RB0 an output high and RB5 an
input (to present a high impedance).
2. Perform two successive A/D conversions,
first on AN0, then on AN1.
3. Save the conversion results to their respective
variables; for example, RB0_AN0_Result
and RB0_AN1_Result.
4. Next, make RB5 an output high and RB0 an
input (to present a high impedance).
5. Perform two successive A/D conversions,
first on AN0, then on AN1.
6.
Save the conversion results to their respective
variables; for example, RB5_AN0_Result
and RB5_AN1_Result.
7. There are now 4 variables that represent
a key press in each quadrant of the 4 x 4
keypad:
- RB0_AN0_Result
denotes key press of 1, 2, 4 or 5
- RB0_AN1_Result
denotes key press of 7, 8, A or 0
- RB5_AN0_Result
denotes key press of 3, C, 6 or D
- RB5_AN1_Result
denotes key press of 9, E, B or F
© 2009 Microchip Technology Inc.Page 6-12-DS01146B
LCD PIC
®
Microcontroller Tips ‘n Tricks
Application Note References
• AN220, “Watt-Hour Meter Using PIC16C923
and CS5460” (DS00220)
• AN582, “Low-Power Real-Time Clock
(DS00582)
• AN587, “Interfacing PIC® MCUs to an LCD
Module” (DS00587)
• AN649, “Yet Another Clock Featuring the
PIC16C924” (DS00649)
• AN658, “LCD Fundamentals Using
PIC16C92X Microcontrollers” (DS00658)
• TB084, “Contrast Control Circuits for the
PIC16F91X” (DS91084)
Application notes can be found on the Microchip
web site at www.microchip.com.
© 2009 Microchip Inc. DS01146B-Page 7-1
Intelligent Power Supply Design Tips ‘n Tricks
Table Of Contents
TIPS ‘N TRICKS INTRODUCTION
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
CHAPTER 7
Intelligent Power Supply Design
Tips ‘n Tricks
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.
While some designs such as Switch Mode
Power Supplies (SMPS) are traditionally
implemented using a purely analog control
scheme, these designs can benefit from the
configurability and intelligence that can only be
realized by adding a microcontroller.
This document showcases several examples
in which a PIC microcontroller may be used
to increase the functionality of a design with a
minimal increase in cost.
Several of the tips provide working software
examples or reference other documents for
more information. The software and referenced
documents can be found on the Microchip web
site at www.microchip.com/tipsntricks.
© 2009 Microchip Inc.Page 7-2-DS01146B
Intelligent Power Supply Design Tips ‘n Tricks
TIP #1 Soft-Start Using a PIC10F200
Almost all power supply controllers are
equipped with shutdown inputs that can be used
to disable the MOSFET driver outputs. Using
Pulse-Width Modulation (PWM), the amount
of time the power supply is allowed to operate
can be slowly incremented to allow the output
voltage to slowly rise from 0% to 100%.
Figure 1-1: Soft-Start Circuit Schematic
N.C.N.C. XX
V
On/Off
Control
Input
V
DD
Shutdown
PWM Output
0.1 µF
5
3
GP0 GP1
GP2GP3
6
1
2
4
10 k
Note: Assumes SOT-23 packaging.
This technique is called soft-start and is used to
prevent the large inrush currents that are
associated with the start-up of a switching
power supply.
GP0 on the PIC MCU is used to enable or
disable the soft-start. Once enabled, the on-time
of the PWM signal driving the shutdown output
will increase each cycle until the power supply
is fully on.
During the PIC MCU Power-on Reset, the PWM
output (GP1) is initially in a high-impedance
state. A pull-down resistor on the PWM output
ensures the power supply will not unexpectedly
begin operating.
Figure 1-2: Timing Diagram
Output Voltage
PWM
100%
0%
It is important to note that this type of soft-start
controller can only be used for switching
regulators that respond very quickly to changes
on their shutdown pins (such as those that do
cycle-by-cycle limiting). Some linear regulators
have active-low shutdown inputs, however,
these regulators do not respond fast enough to
changes on their shutdown pins in order to
perform soft-start.
Example software is provided for the
PIC10F200 which was taken from TB081.
Please refer to TB081, “Soft-Start Controller For
Switching Power Supplies” (DS91081) for more
information.
© 2009 Microchip Inc. DS01146B-Page 7-3
Intelligent Power Supply Design Tips ‘n Tricks
TIP #2 A Start-Up Sequencer
Some new devices have multiple voltage
requirements (e.g., core voltages, I/O voltages,
etc.). The sequence in which these voltages rise
and fall may be important.
By expanding on the previous tip, a start-up
sequencer can be created to control two output
voltages. Two PWM outputs are generated
to control the shutdown pins of two SMPS
controllers. Again, this type of control only works
on controllers that respond quickly to changes
on the shutdown pin (such as those that do
cycle-by-cycle limiting).
Figure 2-1: Multiple PWM Output Soft-Start
Controller
10 k
Note: Assumes SOT-23 packaging.
0.1 µF
Shutdown
VDD
5
3
GP0/CIN+ GP1
GP2GP3
6
1
2
4
10 k
PWM Output #1
PWM Output #2
Under-
Voltage
Lockout
This design uses the PIC MCU comparator to
implement an under-voltage lockout. The input
on the GP0/Ci n + pin must be above the internal
0.6V reference for soft-start to begin, as shown
in Figure 2-2.
Two conditions must be met in order for the
soft-start sequence to begin:
1. The shutdown pin must be held at Vd d
(logic high).
2. The voltage on GP0 must be above 0.6V.
Once both start-up conditions are met, the
sequences will delay and PWM #1 will ramp
from 0% to 100%. A second delay allows the
first voltage to stabilize before the sequencer
ramps PWM #2 from 0% to 100%. All delays
and ramp times are under software control and
can be customized for specific applications. If
either soft-start condition becomes invalid, the
circuit will shutdown the SMPS controllers.
Figure 2-2: Timing Diagram
V1
PWM1
1. Start-up conditions met
2. Initial delay
3. PWM Ramp #1 complete
4. Between PWM delay
5. PWM #2 complete
12
PWM2
34 5
V2
Example software is provided for the
PIC10F200 which was taken from TB093,
Multiple PWM Output Soft-Start Controller for
Switching Power Supplies” (DS91093).
© 2009 Microchip Inc.Page 7-4-DS01146B
Intelligent Power Supply Design Tips ‘n Tricks
TIP #3 A Tracking and Proportional
Soft-Start of Two Power
Supplies
Expanding on the previous tip, we can also
use a PIC MCU to ensure that two voltages in
a system rise together or rise proportionally to
one another, as shown in Figure 3-1. This type
of start-up is often used in applications with
devices that require multiple voltages (such as
I/O and core voltages).
Like the previous two, this tip is designed to
control the shutdown pin of the SMPS controller
and will only work with controllers that respond
quickly to changes on the shutdown pin.
Figure 3-1: Timing Diagram
Time
V
A
V
B
Voltage
Figure 3-2: Example Schematic
Control
Software
Shutdown
0.1 µF
PIC12F629
+
-
VDD
Resistor
Divider 2
VB
VA
Resistor
Divider 1
Shutdown A
Shutdown B
R
1
R
2
The comparator of the PIC MCU is used to
determine which voltage is higher and increases
the on-time of the other output accordingly. The
logic for the shutdown pins is as shown in Table
3-1.
Table 3-1: Shutdown Pin Logic
Case Shutdown
A
Shutdown
B
Va > VbLow High
Vb > VaHigh Low
Vb > Internal Reference High High
To determine if it has reached full voltage, Vb is
compared to the internal voltage reference. If Vb
is higher, both shutdown outputs are held high.
Resistor Divider 1 should be designed so that
the potentiometer output is slightly higher than
the comparator voltage reference when Vb is at
full voltage.
The ratio of resistors in Resistor Divider 2 can
be varied to change the slope at which Va rises.
Pull-down resistors ensure the power supplies
will not operate unexpectedly when the PIC
MCU is being reset.
© 2009 Microchip Inc. DS01146B-Page 7-5
Intelligent Power Supply Design Tips ‘n Tricks
TIP #4 Creating a Dithered PWM
Clock
In order to meet emissions requirements as
mandated by the FCC and other regulatory
organizations, the switching frequency of a
power supply can be varied. Switching at a fixed
frequency produces energy at that frequency.
By varying the switching frequency, the energy
is spread out over a wider range and the
resulting magnitude of the emitted energy at
each individual frequency is lower.
The PIC10F200 has an internal 4 MHz
oscillator. A scaled version of oscillator can be
output on a pin (Fosc/4). The scaled output
is 1/4 of the oscillator frequency (1 MHz) and
will always have a 50% duty cycle. Figure 4-1
shows a spectrum analyzer shot of the output of
the Fosc/4 output.
Figure 4-1: Spectrum of Clock Output
Before Dithering
10 dB/REF 20 dBm
Center 1.0 MH zSpan 1.8 MHz
The PIC10F200 provides an Oscillator
Calibration (OSCCAL) register that is used
to calibrate the frequency of the oscillator. By
varying the value of the OSCCAL setting, the
frequency of the clock output can be varied.
A pseudo-random sequence was used to vary
the OSCCAL setting, allowing frequencies
from approximately 600 kHz to 1.2 MHz. The
resulting spectrum is shown in Figure 4-2.
Figure 4-2: Spectrum of Clock Output
After Dithering
10 dB/REF 20 dBm
Center 1.0 MH zSpan 1.8 MHz
By spreading the energy over a wider range of
frequencies, a drop of more than 20 dB is
achieved.
Example software is provided for the
PIC10F200 that performs the pseudo-random
sequence generation and loads the OSCCAL
register.
© 2009 Microchip Inc.Page 7-6-DS01146B
Intelligent Power Supply Design Tips ‘n Tricks
The switching frequency of the MCP1630 can
be adjusted by changing the frequency of the
clock source. The maximum on-timer of the
MCP1630 PWM can be adjusted by changing
the duty cycle of the clock source.
The PIC MCU has several options for providing
this clock source:
• The Fosc/4 pin can be enabled. This will
produce a 50% duty cycle square wave that
is 1/4th of the oscillator frequency. Tip #4
provides both example software and
information on clock dithering using the Fo s c /4
output.
• For PIC MCUs equipped with a Capture/
Compare/PWM (CCP) or Enhanced CCP
(ECCP) module, a variable frequency, variable
duty cycle signal can be created with little
software overhead. This PWM signal is entirely
under software control and allows advanced
features, such as soft-start, to be implemented
using software.
• For smaller parts that do not have a CCP
or ECCP module, a software PWM can be
created. Tips #1 and #2 use software PWM for
soft-start and provide software examples.
TIP #5
Using a PIC
®
Microcontroller
as a Clock Source for a SMPS
PWM Generator
A PIC MCU can be used as the clock source for
a PWM generator, such as the MCP1630.
Figure 5-1: PIC MCU and MCP1630 Example
Boost Application
C1
FB
MCP1630
V
IN
PC
MC
V
IN
V
EXT
CS
OSC IN R2
R1
M1
D1
L1
R
SENSE
The MCP1630 begins its cycle when its clock/
oscillator source transitions from high-to-low,
causing its PWM output to go high state. The
PWM pulse can be terminated in any of three
ways:
1. The sensed current in the magnetic device
reaches 1/3 of the error amplifier output.
2. The voltage at the Feedback (FB) pin is
higher than the reference voltage (Vr e f ).
3. The clock/oscillator source transitions from
low-to-high.
© 2009 Microchip Inc. DS01146B-Page 7-7
Intelligent Power Supply Design Tips ‘n Tricks
It is possible to implement the current limiting
by using a single sense resistor. In this case,
the maximum current would be given by
Equation 6-1.
Equation 6-1
For high current applications, this method may
be acceptable. When lower current limits are
required, the size of the sense resistor, Rs e n s e ,
must be increased. This will cause additional
power dissipation. An alternative method for
lower current limits is shown in Figure 6-2.
Figure 6-2: Low Current Limits
CS Input
L1
R
SENSE
V
DD
R2
+
R1
In this case, the Current Sense (CS) input of the
MCP1630 is biased upward using the R1/R2
resistor divider. The equations for the new
current limit are shown in Equation 6-2.
Equation 6-2
Equation 6-2 can be solved to determine the
values of R1 and R2 that provide the desired
current limit.
TIP #6 Current Limiting Using the
MCP1630
Figure 6-1: MCP1630 High-Speed PWM
OSC IN
100 k
+
-
V
IN
UVLO
0.1 µA
S
R
+
-
GND
V
IN
V
EXT
Overtemperature
(1)
Q
Q
Comp
CS
V
IN
0.1 µA
Comp
V
IN
V
REF
FB
EA
R
2R
2.7V Clamp
Note 1: During overtemperature, V
EXT
driver is high-impedance.
t t e
00Qn
011
100
111
The block diagram for the MCP1630 high-speed
PWM driver is shown in Figure 6-1. One of the
features of the MCP1630 is the ability to
perform current limiting. As shown in the bottom
left corner of the diagram, the output of the
Error Amplifier (EA) is limited by a 2.7V clamp.
Therefore, regardless of the actual error, the
input to the negative terminal of the comparator
(labeled Comp) is limited to 2.7V ÷ 3 or 0.9V.
Im a x = (0.9V) / Rs e n s e
0.9V = (Vd d - Im a x Rs e n s e ) R2
R1 + R2
© 2009 Microchip Inc.Page 7-8-DS01146B
Intelligent Power Supply Design Tips ‘n Tricks
Figure 7-2: Desired and Actual Inductor
Currents
Reference
Inductor
Current
Actual
Inductor
Current
A PIC MCU has several features that allow it to
perform power factor correction.
• The PIC MCUs CCP module can be used to
generate a PWM signal that, once filtered, can
be used to generate the sine wave reference
signal.
• The PIC Analog-to-Digital (A/D) converter can
be used to sense VBoost and the reference
sine wave can be adjusted in software.
• The interrupt-on-change feature of the PIC
MCU input pins can be used to allow the PIC
MCU to synchronize the sine wave reference
to the line voltage by detecting the zero
crossings.
• The on-chip comparators can be used for
driving the boost MOSFET(s) using the PWM
sine wave reference as one input and the
actual inductor current as another.
TIP #7 Using a PIC
®
Microcontroller
for Power Factor Correction
In AC power systems, the term Power Factor
(PF) is used to describe the fraction of power
actually used by a load compared to the total
apparent power supplied.
Power Factor Correction (PFC) is used to
increase the efficiency of power delivery by
maximizing the PF.
The basis for most Active PFC circuits is a boost
circuit, shown in Figure 7-1.
Figure 7-1: Typical Power Factor Correction
Boost Supply
PWM
M1
C2
+
C1
VBoost
+
+
-
+ -
L1 D1
The AC voltage is rectified and boosted to
voltages as high as 400 Vd c . The unique feature
of the PFC circuit is that the inductor current is
regulated to maintain a certain PF. A sine wave
reference current is generated that is in phase
with the line voltage. The magnitude of the sine
wave is inversely proportional to the voltage at
Vboost. Once the sine wave reference is
established, the inductor current is regulated to
follow it, as shown in Figure 7-2.
© 2009 Microchip Inc. DS01146B-Page 7-9
Intelligent Power Supply Design Tips ‘n Tricks
Resistive Power Supply
Figure 8-2: Resistive Power Supply
V
OUT
R1
1K 5W
L
D1
5.1V
I
OUT
N
I
IN
D2
C2
R2
1K 5W
The resistive power supply works in a similar
manner to the capacitive power supply by using
a reversed-biased Zener diode to produce the
desired voltage. However, R1 is much larger
and is the only current limiting element.
Advantages:
• Significantly smaller than a transformer-based
power supply
• Lower cost than a transformer-based power
supply
• Lower cost than a capacitive power supply
Disadvantages:
• Not isolated from the AC line voltage which
introduces safety issues
• Power supply is less energy efficient than a
capacitive power supply
• More energy is dissipated as heat in R1
More information on either of these solutions,
including equations used for calculating
circuit parameters, can be found in AN954,
Transformerless Power Supplies: Resistive
and Capacitive” (DS00954) or in TB008,
Transformerless Power Supply” (DS91008).
TIP #8 Transformerless Power
Supplies
When using a microcontroller in a line-powered
application, such as the IR remote control
actuated AC switch described in Tip #9, the
cost of building a transformer-based AC/DC
converter can be significant. However, there
are transformerless alternatives which are
described below.
Capacitive Transformerless Power Supply
Figure 8-1: Capacitive Power Supply
470 1/2W
V
OUT
R1
C1
L
D1
5.1V
I
OUT
N
I
IN
.47µ 250V D2
C2
470 µF
Figure 8-1 shows the basics for a capacitive
power supply. The Zener diode is reverse-
biased to create the desired voltage. The
current drawn by the Zener is limited by R1 and
the impedance of C1.
Advantages:
• Significantly smaller than a transformer-based
power supply
• Lower cost than a transformer-based or
switcher-based power supply
• Power supply is more efficient than a resistive
transformerless power supply
Disadvantages:
• Not isolated from the AC line voltage which
introduces safety issues
• Higher cost than a resistive power supply
because X2 rated capacitors are required
© 2009 Microchip Inc.Page 7-10-DS01146B
Intelligent Power Supply Design Tips ‘n Tricks
TIP #9 An IR Remote Control
Actuated AC Switch for
Linear Power Supply Designs
Many line-powered applications (audio
amplifiers, televisions, etc.) can be turned on
and off using an infrared remote control. This
requires that some components be energized
to receive the remote signals even when the
device is off. Low current PIC microcontrollers
are best in this application. Figure 9-1 shows an
example circuit layout.
Figure 9-1: PIC MCU Infrared Receiver
Schematic
Zero Crossing
Detection
+
-
Do
C2
C1
Load
Load
R1
AC IN
Q1
R2
+5V
GP0/C+
VSS
VDD
U1
GP1/C-
GP2/COUT
GP2/MCLR
The PIC10F200 has several features that make
it ideally suited for this type of application:
• Extremely low operating and standby current
(350 µA operating, 0.1 µA when asleep)
• Input/Output pins with configurable pull-ups
and reset-on-change capability
• High sink/source ability (±25 mA) allows
driving external devices, such as the IR
receiver, directly from the I/O pin
• Ability to use a low-cost resistive power supply
• Small form factor (SOT-23 packaging)
TB094, “Dimming AC Incandescent Lamps
Using A PIC10F200” (DS91094) provides both
software and hardware examples of an infrared
controller.
© 2009 Microchip Inc. DS01146B-Page 7-11
Intelligent Power Supply Design Tips ‘n Tricks
TIP #10 Driving High Side FETs
In applications where high side N channel FETs
are to be driven, there are several means for
generating an elevated driving voltage. One
very simple method is to use a voltage doubling
charge pump as shown in Figure 10-1.
Method 1
Figure 10-1: Typical Change Pump
VDD
D1
CFILTER
CPUMP D2
VOUT max =
2 * VDD - 2 * VDIODE
CLKOUT
The PIC MCUs CLKOUT pin toggles at 1/4 of
the oscillator frequency. When CLKOUT is low,
D1 is forward biased and conducts current,
thereby charging Cp u m p . After CLKOUT is high,
D2 is forward biased, moving the charge to
Cf i l t e r . The result is a voltage equal to twice
the Vd d minus two diode drops. This can be
used with a PWM or any other I/O pin that
toggles.
In Figure 10-2, a standard FET driver is used to
drive both the high and low side FETs by using
the diode and capacitor arrangement.
Method 2
Figure 10-2: Schematic
+5V
D1 D2
C2
FET Driver
M1
C1
PWM1
PWM2
M2
L1
U1A
U1B
+12V
The +5V is used for powering the microcontroller.
Using this arrangement, the FET driver would
have approximately 12 + (5 - Vd i o d e ) - Vd i o d e
volts as a supply and is able to drive both the
high and low side FETs.
The circuit above works by charging C1 through
D1 to (5V - Vd i o d e ) while M2 is on, effectively
connecting C1 to ground. When M2 turns off
and M1 turns on, one side of C1 is now at 12V
and the other side is at 12V + (5V - Vd i o d e ). The
D2 turns on and the voltage supplied to the FET
driver is 12V + (5V - Vd i o d e ) - Vd i o d e .
© 2009 Microchip Inc.Page 7-12-DS01146B
Intelligent Power Supply Design Tips ‘n Tricks
R and C are chosen based on the following
equation:
Equation 11-2
Choose the R value based on drive capability
and then calculate the required C value. The
attenuation of the PWM frequency for a given
RC filter is shown in Equation 11-3.
Equation 11-3
If the attenuation calculated in Equation 11-3
is not sufficient, then K must be increased in
Equation 11-1.
In order to sufficiently attenuate the harmonics,
it may be necessary to use small capacitor
values or large resistor values. Any current
draw will effect the voltage across the capacitor.
Adding an op amp allows the analog voltage to
be buffered and, because of this, any current
drawn will be supplied by the op amp and not
the filter capacitor.
For more information on using a PWM signal
to generate an analog output, refer to AN538,
Using PWM to Generate Analog Output
(DS00538).
TIP #11 Generating a Reference
Voltage with a PWM Output
Figure 11-1: Low-Pass Filter
Analog
Out
CCP1
MCP6001
C
R
+
-
A PWM signal can be used to create a Digital-
to-Analog Converter (DAC) with only a few
external components. Conversion of PWM
waveforms to analog signals involves the use of
an analog low-pass filter. In order to eliminate
unwanted harmonics caused by a PWM signal,
the PWM frequency (Fp w m ) should be
significantly higher than the bandwidth (Fb w ) of
the desired analog signal. Equation 11-1 shows
this relation.
Equation 11-1
Fp w m = K • Fb w
Where harmonics decrease as K increases.
RC = 1/(2 • p • Fb w )
Where harmonics decrease as K increases.
Att(dB) = -10 • log [1 + (2 p • Fp w m rc) 2]
© 2009 Microchip Inc. DS01146B-Page 7-13
Intelligent Power Supply Design Tips ‘n Tricks
TIP #12 Using Auto-Shutdown CCP
PWM Auto-Shutdown
Several of Microchip’s PIC MCUs, such as the
PIC16F684, PIC16F685 and PIC16F690, have
a PWM auto-shutdown feature. When auto-
shutdown is enabled, an event can terminate
the current PWM pulse and prevent subsequent
pulses unless the event is cleared. The ECCP
can be setup to automatically start generating
pulses again once the event clears.
Figure 12-1: PWM Auto-Shutdown Timing
Shutdown
Event
PWM Signal
Figure 12-1 shows an example timing for the
PWM auto-shutdown. When the shutdown event
occurs, the current pulse is immediately
terminated. In this example, the next two pulses
are also terminated because the shutdown
event had not been cleared by the beginning of
the pulse period. After the event has cleared,
pulses are allowed to resume, but only at the
beginning of a pulse period.
Using Auto-Shutdown to Create a
Boost Supply
By using the auto-shutdown feature, a very
simple SMPS can be created. Figure 12-2
shows an example boost power supply.
Figure 12-2: Boost Power Supply
D1
L1
+
-
C1
VIN
VOUT
R2
R1
R3
Q1
Internal to PIC
®
MCU
PWM
Module
Out
This power supply configuration has several
unique features:
1. The switching frequency is determined by the
PWM frequency and, therefore, can be
changed at any time.
2. The maximum on-time is determined by the
PWM duty cycle and, therefore, can be
changed any time. This provides a very easy
way to implement soft-start.
3. On PIC MCUs that have a programmable
reference module, the output voltage can be
configured and changed at any time.
The topology can also be re-arranged to create
other types of power supplies.
Example software is provided for the
PIC16F685 (but can be adapted to any PIC
MCU with the ECCP module). The software
configures the PWM and comparator modules
as shown in Figure 12-2.
© 2009 Microchip Inc.Page 7-14-DS01146B
Intelligent Power Supply Design Tips ‘n Tricks
In order to configure the ECCP to produce this
type of output:
1. Configure the ECCP in half H-bridge
configuration PWM pulse with both outputs
active-high.
2. Set the duty cycle register (CCPR1L) with the
maximum duty cycle of 50%.
3. Change the programmable dead-time
generator to reduce the pulse width to the
desired value.
The programmable dead-time generator has
a 7-bit resolution and, therefore, the resulting
pulses will only have a 7-bit resolution. Each
pulse will have a 50% duty cycle, less the dead
time.
Using an internal 4 MHz clock produces 31 kHz
output pulses, and using a 20 MHz crystal
would produce 156 kHz output. The frequency
of the output could be increased with a loss in
resolution.
Example software is provided for the
PIC16F684, but this tip is applicable to all PIC
MCUs with ECCP modules.
TIP #13 Generating a Two-Phase
Control Signal
Power supplies using a push-pull topology or
with multiple switching components require a
two-phase control signal as shown in Figure
13-1.
Figure 13-1: Two-Phase Control Signal
P1A
P1B
It is possible to produce this type of control
signal with two out-of-phase square waves
using a PIC MCU with an ECCP module.