PIC Microcontroller Compiled Tips 'n Tricks Guide

Compiled Tips ‘N Tricks Guide
© 2009 Microchip Technology Inc.
DS01146B
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.
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.
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.
DS01146B-page ii
© 2009 Microchip Technology Inc.
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: Vdd 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...................................................
TIP #2
Power Budgeting.........................................
TIP #3
Configuring Port Pins..................................
TIP #4
Use High-Value Pull-Up Resistors...............
TIP #5
Reduce Operating Voltage..........................
TIP #6
Use an External Source for
CPU Core Voltage.......................................
TIP #7
Battery Backup for PIC MCUs . ..................
DYNAMIC OPERATION TIPS ‘N TRICKS
TIP #8
Enhanced PIC16 Mid-Range Core..............
TIP #9
Two-Speed Start-Up....................................
TIP #10
Clock Switching...........................................
TIP #11
Use Internal RC Oscillators.........................
TIP #12
Internal Oscillator Calibration......................
TIP #13
Idle and Doze Modes..................................
TIP #14
Use NOP and Idle Mode...............................
TIP #15
Peripheral Module Disable
(PMD) Bits...................................................
© 2009 Microchip Technology Inc.
2-2
2-3
2-4
2-4
2-4
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....
TIP #2:
Measuring the Period of a
Square Wave with Averaging......................
TIP #3:
Measuring Pulse Width...............................
TIP #4:
Measuring Duty Cycle.................................
TIP #5:
Measuring RPM Using an Encoder.............
TIP #6:
Measuring the Period of an Analog Signal..
3-3
3-3
3-4
3-4
3-5
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
2-5
2-6
2-6
2-7
2-7
2-7
2-8
2-8
2-9
2-9
Page i-DS01146B
Tips ‘n Tricks Table of Contents
PIC® Microcontroller Comparator
Tips ‘n Tricks
Intelligent Power Supply Design
Tips ‘n Tricks
TIP #1:
TIP #2:
TIP #3:
TIP #4:
TIP #5:
TIP #6:
TIP #7:
TIP #8:
TIP #9:
TIP #10:
TIP #11:
TIP #12:
TIP #13:
TIP #14:
TIP #15:
TIP #16:
TIP #17:
TIP #18:
TIP #19:
TIP #20:
TIP #1:
TIP #2:
TIP #3:
TIP #4:
TIP #5:
TIP #6:
TIP #7:
TIP #8:
TIP #9:
TIP #10:
TIP #11:
TIP #12:
TIP #13:
TIP #14:
TIP #15:
TIP #16:
TIP #17:
TIP #18:
TIP #19:
TIP #20:
TIP #21:
Low Battery Detection................................. 4-2
Faster Code for Detecting Change............. 4-3
Hysteresis................................................... 4-4
Pulse Width Measurement.......................... 4-5
Window Comparison................................... 4-6
Data Slicer................................................... 4-7
One-Shot..................................................... 4-8
Multi-Vibrator (Square Wave Output).......... 4-9
Multi-Vibrator (Ramp Wave Output)............4-10
Capacitive Voltage Doubler.........................4-11
PWM Generator..........................................4-12
Making an Op Amp Out of a Comparator....4-13
PWM High-Current Driver...........................4-14
Delta-Sigma ADC........................................4-15
Level Shifter................................................4-16
Logic: Inverter.............................................4-16
Logic: AND/NAND Gate..............................4-17
Logic: OR/NOR Gate..................................4-18
Logic: XOR/XNOR Gate..............................4-19
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
Page ii-DS01146B
Soft-Start Using a PIC10F200..................... 7-2
A Start-Up Sequencer................................. 7-3
A Tracking and Proportional
Soft-Start of Two Power Supplies................ 7-4
Creating a Dithered PWM Clock................. 7-5
Using a PIC® Microcontroller as a Clock
Source for a SMPS PWM Generator.......... 7-6
Current Limiting Using the MCP1630.......... 7-7
Using a PIC® Microcontroller for
Power Factor Correction............................. 7-8
Transformerless Power Supplies................ 7-9
An IR Remote Control Actuated AC
Switch for Linear Power Supply Designs....7-10
Driving High Side FETs...............................7-11
Generating a Reference Voltage with a
PWM Output................................................7-12
Using Auto-Shutdown CCP.........................7-13
Generating a Two-Phase Control Signal.....7-14
Brushless DC Fan Speed Control...............7-15
High Current Delta-Sigma Based Current
Measurement Using a Slotted Ferrite
and Hall Effect Device.................................7-16
Implementing a PID Feedback Control
in a PIC12F683-Based SMPS Design........7-17
An Error Detection and Restart Controller..7-18
Data-Indexed Software State Machine.......7-19
Execution Indexed Software
State Machine.............................................7-20
Compensating Sensors Digitally.................7-21
Using Output Voltage Monitoring to
Create a Self-Calibration Function..............7-22
3V Tips ‘n Tricks
TIP #1:
TIP #2:
TIP #3:
TIP #4:
TIP #5:
TIP #6:
TIP #7:
TIP #8:
TIP #9:
TIP #10:
TIP #11:
TIP #12:
TIP #13:
TIP #14:
TIP #15:
TIP #16:
TIP #17:
TIP #18:
TIP #19:
Powering 3.3V Systems From 5V
Using an LDO Regulator............................. 8-3
Low-Cost Alternative Power System
Using a Zener Diode................................... 8-4
Lower Cost Alternative Power System
Using 3 Rectifier Diodes.............................. 8-4
Powering 3.3V Systems From 5V
Using Switching Regulators........................ 8-5
3.3V → 5V Direct Connect.......................... 8-6
3.3V → 5V Using a MOSFET Translator..... 8-6
3.3V → 5V Using A Diode Offset................. 8-7
3.3V → 5V Using A Voltage Comparator..... 8-8
5V → 3.3V Direct Connect.......................... 8-9
5V → 3.3V With Diode Clamp..................... 8-9
5V → 3.3V Active Clamp.............................8-10
5V → 3.3V Resistor Divider........................8-10
3.3V → 5V Level Translators......................8-12
3.3V → 5V Analog Gain Block....................8-13
3.3V → 5V Analog Offset Block...................8-13
5V → 3.3V Active Analog Attenuator...........8-14
5V → 3V Analog Limiter..............................8-15
Driving Bipolar Transistors..........................8-16
Driving N-Channel MOSFET Transistors....8-18
© 2009 Microchip Technology Inc.
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: Vdd 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
© 2009 Microchip Technology Inc.
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.
DS01146B-Page 1-1
8-pin Flash PIC® Microcontroller Tips ‘n Tricks
TIP #1Dual Speed RC Oscillator
TIP #2Input/Output Multiplexing
Figure 1-1
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.
+5V
R1
PIC12F6XX
R2
GP0
OSC1
C
The equation is: D = GP x (GP - 1).
Example 2-1: Six LEDs on Three I/O Pins
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
Page 1-2 DS01146B
GPx
0 1 2
LEDs
1 2 3 4 5 6
0
0
1
Z
Z
0
1
0
0
0
1
1
1
1
0
1
0
0
0
0
0
0
1
1
0
0
0
0
0
1
0
0
1
Z
Z
0
1
1
0
0
1
1
0
Z
Z
1
0
1
0
1
0
1
0
1
0
1
0
0
1
0
0
0
0
0
0
0
1
1
0
0
0
0
0
1
0
0
0
1
0
0
0
1
0
0
0
0
0
0
1
0
0
0
1
0
0
0
1
0
0
0
0
0
0
1
0
1
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
1
0
Figure 2-1
PIC12F6XX
GP0
GP1
GP2
2
1
3
5
6
4
© 2009 Microchip Technology Inc.
8-pin Flash PIC® Microcontroller Tips ‘n Tricks
TIP #3Read Three States
From One Pin
To check state Z:
Figure 3-1
•Drive output pin high
•Set to Input
•Read 1
PIC
•Drive output pin low
I/O
•Set to Input
•Read 0
TIP #4Reading DIP Switches
5V
Link 1
Link 0
0V
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.
The input of a timer Example 4-1
can be used to test
movlw
which switch(s)
movwf
movwf
is closed. The
movlw
movwf
input of Timer1 is
movlw
held high with a
movwf
clrf
pull-up resistor.
LOOP
clrf
Sequentially,
movf
each switch I/O is
movwf
btfsc
set to input and
andwf
bsf
Timer1 is checked
rlf
for an increment
btfsc
goto
indicating the
retlw
switch is closed.
TMR1L
Mask,W
TRISIO
TMR1L,0
DIP,F
STATUS,C
Mask,F
Mask,4
Loop
0
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
VDD
PIC12F6XX
10K
GP5/T1CKI
Data I/O
© 2009 Microchip Technology Inc.
b'11111111'
TRISIO
DIP
b'00000111'
T1CON
b'11111110'
Mask
GPIO
GP4
GP3
GP2
GP1
GP0
DS01146B-Page 1-3
8-pin Flash PIC® Microcontroller Tips ‘n Tricks
TIP #5Scanning Many Keys With
One Input
TIP #6Scanning Many Keys and
Wake-up From Sleep
The time required to charge a capacitor
depends on resistance between Vdd and
capacitor. When a button is pressed, Vdd is
supplied to a different point in the resistor
ladder. The resistance between Vdd 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.
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-onchange 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 Vdd 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.
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
CVref as the other.
3. Use a timer to measure when the comparator
trips. If the time measured is greater than the
maximum allowed time, then repeat;
otherwise determine which button is pressed.
• 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
When a key is pressed, the voltage divider
network changes the RC ramp rate.
VDD
Figure 5-1
100R
R
R
R
R
PIC12F6XX
GP5
GP0
GP4
GP1
GP3
GP2
16
Resistors
R
220Ω
R
PIC12F6XX
GP5
16
Resistors
R
GP0
GP4
GP1
GP3
GP2
R
220Ω
See AN512, “Implementing Ohmmeter/
Temperature Sensor” for code ideas.
Page 1-4 DS01146B
© 2009 Microchip Technology Inc.
8-pin Flash PIC® Microcontroller Tips ‘n Tricks
TIP #74x4 Keyboard with 1 Input
TIP #8One Pin Power/Data
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.
A single I/O can be used for both a singledirection communication and the power source
for another microcontroller. The I/O line is held
high by the pull-up resistor connected to Vdd.
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. Vdd is supplied to the sender through
the data line. The capacitor stabilizes the sender’s
Vdd and a diode prevents the capacitor from
discharging through the I/O line while it is low.
Note that the Vdd of the sender is a diode-drop
lower than the receiver.
Figure 7-1
VDD
Figure 8-1
PIC12F6XX
GP0
VDD
Receiver
GP0
© 2009 Microchip Technology Inc.
VDD
VDD - 0.7V
Sender
GP0
DS01146B-Page 1-5
8-pin Flash PIC® Microcontroller Tips ‘n Tricks
TIP #9Decode Keys and ID Settings
TIP #10Generating High Voltages
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 10-1
Figure 9-1
GP0
GP1
GP2
GP3
GP4
VDD
PIC12F6XX
w/RC CLKOUT
VDD
VOUT max = 2 * VDD - 2 * VDIODE
CLKOUT
CPUMP
CFILTER
Voltages greater than Vdd 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 Vdd diode is forward
biased and conducts current, thereby charging
Cpump. After OSC2 is high, the other diode is
forward biased, moving the charge to Cfilter.
The result is a charge equal to twice the Vdd
minus two diode drops. This can be used with a
PWM, a toggling I/O or other toggling pin.
•When GP4 = 1 and no keys are pressed, read
ID setting
•When GP4 = 0, read the switch buttons
Page 1-6 DS01146B
© 2009 Microchip Technology Inc.
8-pin Flash PIC® Microcontroller Tips ‘n Tricks
Building on the previous topic, the same charge
pump can be used by the MCU to supply its
own Vdd. Before the switch is pressed, Vbat
has power and the Vdd points are connected
together but unpowered. When the button is
pressed, power is supplied to Vdd and the
MCUs CLKOUT (in external RC oscillator mode)
begins toggle. The voltage generated by the
charge pump turns on the FET allowing Vdd
to remain powered. To power down the MCU,
execute a Sleep instruction. This allows the
MCU to switch off its power source via software.
TIP #12Using PIC® MCU A/D For
Smart Current Limiter
Figure 12-1
PIC12F6XX
10K
W
TIP #11 Vdd Self Starting Circuit
Load or Motor
AN0
RSENSE
Advantages:
• PIC MCU leakage current nearly 0
• Low cost (uses n-channel FET)
• Reliable
• No additional I/O pins required
•Detect current through low side sense resistor
•Optional peak filter capacitor
•Varying levels of overcurrent response can be
realized in software
Figure 11-1
VBAT
VDD
VDD
VDD
CLKOUT
VDD
By adding a resistor (Rsense) 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.
PIC12F6XX
© 2009 Microchip Technology Inc.
DS01146B-Page 1-7
8-pin Flash PIC® Microcontroller Tips ‘n Tricks
TIP #13Reading a Sensor With
Higher Accuracy
Tip #13.1Reading a Sensor With Higher
Accuracy – RC Timing Method
Sensors can be read directly with the A/D but in
some applications, factors such as temperature,
external component accuracy, sensor nonlinearity 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.
RC Timing Method:
13.1. RC Timing Method (with reference resistor)
Simple RC step response
Vc(t) = Vdd * (1 - e -t/(RC))
t = -RC ln(1 - Vth/Vdd)
Vth/Vdd is constant
R2 = (t2/t1) * R1
Figure 13-1
Vc(t)
13.2.Charge Balancing Method
R1
R2
13.3.A/D Method
VTH
t=0
t = t1
Time
t = t2
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.
Page 1-8 DS01146B
© 2009 Microchip Technology Inc.
8-pin Flash PIC® Microcontroller Tips ‘n Tricks
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 (Rref) and sensor (Rsen) 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.
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 tRsen (GP0 changes to 1)
4. Repeat step 1
5. Set GP0 to an input and GP2 to a high output
6. Measure tRref (GP0 changes to 1)
7. Use film polypropylene capacitor
8. Rth = x Rref tRsen
tRref
Figure 13-2
PIC12F629
RREF
GP2
RSEN
GP1
GP0
Other alternatives: voltage comparator in the
PIC12F6XX to measure capacitor voltage on
GP0.
© 2009 Microchip Technology Inc.
DS01146B-Page 1-9
8-pin Flash PIC® Microcontroller Tips ‘n Tricks
Tip #13.2Reading a Sensor With Higher
Accuracy – Charge Balancing
Method
The comparator and comparator voltage
reference (CVref) on the PIC12F629/675 are
ideal for this application.
1. Sensor charges a capacitor
1. GP1 average voltage = CVref
2. Reference resistor discharges the capacitor
2. Time base as sampling rate
3. Modulate reference resistor to maintain
constant average charge in the capacitor
3. At the end of each time base period:
- If GP1 > CVref, then GP2 Output Low
- If GP1 < CVref, then GP2 Input mode
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.
4. Accumulate the GP2 lows over many samples
5. Number of samples determines resolution
6. Number of GP2 lows determine effective duty
cycle of Rref
Figure 13-3
VDD
PIC12F6XX
CVREF
RSEN
+
GP1
RREF
COUT
-
T1G
GP2
Page 1-10 DS01146B
© 2009 Microchip Technology Inc.
8-pin Flash PIC® Microcontroller Tips ‘n Tricks
Tip #13.3Reading 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 Rsen, 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.
TIP #14Delta-Sigma Converter
The charge on the capacitor on GP1 is
maintained about equal to the CVref by the
MCU monitoring Cout and switching GP2 from
Input mode or output low appropriately. A timer
is used to sample the Cout 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
Summary:
High range: GP1 output ‘1’ and GP2 input
Low range: GP1 input and GP2 output ‘1’
1. 10K and 100K resistors are used to set the
range
2. Vref for A/D = Vdd
3. Rth calculation is independent of Vdd
PIC12F6XX
CVREF
VIN
GP1
COUT
+
-
GP2
4. Count = Rsen/(Rsen+Rref) x 255
5. Don’t forget to allow acquisition time for the
A/D
1. GP1 average voltage = CVref
Figure 13-4
PIC12F675
100K
GP2
10K
2. Time base as sampling rate
3. At the end of each time base period:
- If GP1 > CVref, then GP2 Output Low
- If GP1 < CVref, then GP2 Output High
GP1
4. Accumulate the GP2 lows over many
samples
AN0 (A/D Input)
5. Number of samples determines resolution
RSEN
© 2009 Microchip Technology Inc.
DS01146B-Page 1-11
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 #15Delay 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
Rtrn
;2 instructions, 2 cycles
$+1
CALL Rtrn
. . .
RETURN
;1 instruction, 2 cycles
;1 instruction, 4 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.
Page 1-12 DS01146B
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.
8-pin Flash PIC® Microcontroller Tips ‘n Tricks
TIP #16Optimizing Destinations
TIP #17Conditional Bit Set/Clear
• Destination bit determines W for F for result
• Look at data movement and restructure
•To move single bit of data from REGA to
REGB
•Precondition REGB bit
•Test REGA bit and fix REGB if necessary
Example 16-1
Example: A + B → A
MOVF
ADDWF
MOVWF
A,W
B,W
A
3 instructions
MOVF
ADDWF
Example 17-1
B,W
A,F
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.
BTFSS
BCF
BTFSC
BSF
REGA,2
REGB,5
REGA,2
REGB,5
4 instructions
BCF
REGB,5
BTFSC REGA,2
BSF
REGB,5
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.
DS01146B-Page 1-13
8-pin Flash PIC® Microcontroller Tips ‘n Tricks
TIP #18Swap File Register with W
TIP #19Bit Shifting Using Carry Bit
Example 18-1
Rotate a byte through carry without using RAM
variable for loop count:
SWAPWF
MACRO
XORWF
XORWF
XORWF
ENDM
REG
REG,F
REG,W
REG,F
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
Page 1-14 DS01146B
• 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
equ
0x20
buffer
STATUS,C
buffer,f
GPIO,Dout
STATUS,C
GPIO,Dout
STATUS,C
buffer,f
buffer,f
STATUS,Z
Send_Loop
;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.
PIC® Microcontroller Low Power Tips ‘n Tricks
CHAPTER 2
PIC® Microcontroller Low Power
Tips ‘n Tricks
Table Of Contents
TIPS ‘N TRICKS INTRODUCTION
GENERAL LOW POWER TIPS ‘N TRICKS
TIP #1 Switching Off External Circuits/
Duty Cycle...........................................
TIP #2 Power Budgeting.................................
TIP #3 Configuring Port Pins..........................
TIP #4 Use High-Value Pull-Up Resistors.......
TIP #5 Reduce Operating Voltage..................
TIP #6 Use an External Source for
CPU Core Voltage...............................
TIP #7 Battery Backup for PIC MCUs . ..........
2-2
2-3
2-4
2-4
2-4
DYNAMIC OPERATION TIPS ‘N TRICKS
TIP #8 Enhanced PIC16 Mid-Range Core......
TIP #9 Two-Speed Start-Up............................
TIP #10 Clock Switching...................................
TIP #11 Use Internal RC Oscillators.................
TIP #12 Internal Oscillator Calibration..............
TIP #13 Idle and Doze Modes..........................
TIP #14 Use NOP and Idle Mode.......................
TIP #15 Peripheral Module Disable
(PMD) Bits...........................................
2-6
2-7
2-7
2-7
2-8
2-8
2-9
2-5
2-6
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
© 2009 Microchip Technology Inc.
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.
DS01146B-Page 2-1
PIC® Microcontroller Low Power Tips ‘n Tricks
TIP #1Switching Off External
Circuits/Duty Cycle
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.
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
C2
0.1 µF
C1
0.1 µF
1k
R4
R5
10k
MCLR
R3
3.3V
10k
R2
100k
U1
VDD
U2
RA0
RB0/INT
RA1
RB1
VCC
A0
RA2
RB2
WP
A1
RA3
RB3
SCL
A2
RA4/TOCKI
RB4
SDA
GND
RB5
Serial EEPROM
Y1
RB6
32.768 kHz
C5
PIC16F819
C4
VSS
33 pF
OSC2/CLKOUT RB7
33 pF
C3
22 pF
OSC1/CLKIN
R1
100k
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.
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.
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.
Figure: 1-2
C2
0.1 µF
C1
0.1 µF
1k
R4
10k
R5
MCLR
R3
3.3V
10k
R2
100k
U1
VDD
U2
RA0
RB0/INT
RA1
RB1
VCC
A0
RA2
RB2
WP
A1
RA3
RB3
SCL
A2
RA4/TOCKI
RB4
SDA
GND
RB5
C5
33 pF
32.768 kHz
C4
VSS
PIC16F819
Page 2-2-DS01146B
Serial EEPROM
Y1
RB6
OSC2/CLKOUT RB7
33 pF
22 pF
R1
100k
C3
OSC1/CLKIN
© 2009 Microchip Technology Inc.
PIC® Microcontroller Low Power Tips ‘n Tricks
TIP #2Power Budgeting
Computing Battery Life
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.
Time
in
Mode
(mS)
Mode
Sleep
MCU Sleep
Sensor Off
EEPROM Off
Initialize
MCU Sleep
Sensor On
EEPROM Off
Sample Sensor
MCU Run
Sensor On
EEPROM Off
Scaling
MCU Run
Sensor Off
EEPROM Off
Storing
MCU Run
Sensor Off
EEPROM On
Total
Current (mA)
Charge
Current *
Time
(mA * Sec)
By
Device
Mode
Total
1989
0.00005
0
0
5.00E-05
9.95E-05
1
0.00005
0.0165
0
1.66E-02
1.66E-05
1
0.048
0.0165
0
6.45E-02
6.45E-05
1
0.048
0
0
4.80E-02
4.80E-05
8
0.048
0
1
1.05E+00
8.38E-03
2000
—
—
8.61E-03
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.
Life
Capacity
(mAh)
Hours
Days
Months
Years
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
Battery
CR1212
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.
Average Current
=
8.61e-3
2000e-3
=
0.0043 mA
Peak Current
© 2009 Microchip Technology Inc.
mA*Sec
Sec
1.05 mA
DS01146B-Page 2-3
PIC® Microcontroller Low Power Tips ‘n Tricks
TIP #3Configuring 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 Vdd or Vss.
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 Vdd or Vss). 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 Vdd
or Vss. If the input voltage is near the midpoint
between Vdd and Vss, 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
TIP #4Use 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 #5Reduce Operating Voltage
Reducing the operating voltage of the device,
Vdd, 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.
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 Vdd and Vss. 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.
Page 2-4-DS01146B
© 2009 Microchip Technology Inc.
PIC® Microcontroller Low Power Tips ‘n Tricks
TIP #6Use an External Source for
CPU Core Voltage
Some PIC MCUs such as “J” type devices (ex.
PIC18F87J90 or PIC24FJ64GA004) use separate 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 regulator powers the core at the nominal voltage that
allows full speed operation. However, if an
application doesn’t require full speed, it is beneficial 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
Example 2: Non-Constant Voltage Source
If the source for Vdd 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:
®
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:
®
© 2009 Microchip Technology Inc.
DS01146B-Page 2-5
PIC® Microcontroller Low Power Tips ‘n Tricks
TIP #7Battery Backup for PIC MCUs
Dynamic Operation Tips n’ Tricks
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 supplied. 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 referenced to VEXT and VBAT in order to monitor
the voltage levels of the battery and the external 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 Vdd caused by the diode turn-on
delay when switching supplies, ensure enough
decoupling capacitance is used on Vdd (C1).
Figure 7-1:
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 #8Enhanced 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.






Page 2-6-DS01146B

© 2009 Microchip Technology Inc.
PIC® Microcontroller Low Power Tips ‘n Tricks
TIP #9Two-Speed Start-Up
TIP #10Clock Switching
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 Startup”) 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.
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.
Example:
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.
Tcy
(Instruction Time)
Instruction
ORG 0x05
125 ms @ 32 kHz
125 ms @ 32 kHz
BSF STATUS,RP0
;bank1
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
;Reset vector
500 ns
application code
500 ns
application code
…
….
..
…
(eventually OST expires, 20 MHz crystal clocks the device)
200 ns
…
application code
….
..
…
© 2009 Microchip Technology Inc.
TIP #11 Use Internal RC Oscillators
DS01146B-Page 2-7
PIC® Microcontroller Low Power Tips ‘n Tricks
TIP #12Internal Oscillator Calibration
TIP #13Idle and Doze Modes
An internal RC oscillator calibrated from the
factory may require further calibration as the
temperature or Vdd 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
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.
Figure 12-1:Timer1 Used to Calibrate an
Internal Oscillator
PIC16F818/819
C1
33 pF
T1OSI
XTAL
32.768 kHz
C2
33 pF
T1OSO
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
(Fosc/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.
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.
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.
Page 2-8-DS01146B
© 2009 Microchip Technology Inc.
PIC® Microcontroller Low Power Tips ‘n Tricks
TIP #14Use 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.
TIP #15Peripheral 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.
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();
}
© 2009 Microchip Technology Inc.
DS01146B-Page 2-9
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 #16Deep 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 wakeup. 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 #17Extended 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 #18Low 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 realtime 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.
Page 2-10-DS01146B
© 2009 Microchip Technology Inc.
PIC® Microcontroller Low Power Tips ‘n Tricks
TIP #19Low Power Timer1 Oscillator
Layout
TIP #20Use LVD to Detect Low
Battery
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.
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.
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
OSC1
OSC2
RB7
RB6
TIP #21Use 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.
RB5
© 2009 Microchip Technology Inc.
DS01146B-Page 2-11
PIC® Microcontroller Low Power Tips ‘n Tricks
TIP #22Ultra 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 wakeup 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
C
I
VREF
Pin Wake-on-Change
Interrupt
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.
Page 2-12-DS01146B
© 2009 Microchip Technology Inc.
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
CHAPTER 3
PIC® Microcontroller CCP and ECCP
Tips ‘n Tricks
Table Of Contents
CAPTURE TIPS ‘N TRICKS
TIP #1 Measuring the Period of a
Square Wave.......................................
TIP #2 Measuring the Period of a
Square Wave with Averaging..............
TIP #3 Measuring Pulse Width.......................
TIP #4 Measuring Duty Cycle.........................
TIP #5 Measuring RPM Using an Encoder.....
TIP #6 Measuring the Period of an
Analog Signal......................................
TIPS ‘N TRICKS INTRODUCTION
3-3
3-3
3-4
3-4
3-5
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
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.
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.
DS01146B-Page 3-1
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
ECCP/CCP Register Listing
Capture
Mode
Select mode
Compare
Mode
Select mode
Timer1
capture
(LSB)
Timer1
capture
(MSB)
Set CCPx
pin to input
Timer1 on,
prescaler
N/A
Timer1
compare
(LSB)
Timer1
compare
(MSB)
Set CCPx pin
to output
Timer1 on,
prescaler
N/A
PWM1CON(1)
N/A
Timer1
interrupt
enable
Timer1
interrupt flag
Global/
peripheral
interrupt
enable
N/A
N/A
Timer1
interrupt
enable
Timer1
interrupt flag
Global/
peripheral
interrupt
enable
N/A
ECCPAS(1)
N/A
N/A
CCPxCON
CCPRxL
CCPRxH
TRISx
T1CON
T2CON
PR2
PIE1
PIR1
INTCON
Note 1: Only on ECCP module.
CAPTURE TIPS ‘N TRICKS
PWM Mode
Select mode,
LSB of duty
cycle
MSB of duty
cycle
N/A
Set CCPx pin(s)
to output(s)
N/A
Timer2 on,
prescaler
Timer2 period
Timer2 interrupt
enable
Timer2 interrupt
flag
Global/
peripheral
interrupt enable
Set dead band,
auto-restart
control
Auto-shutdown
control
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: Falling Edge
Event: Rising Edge
Time
Page 3-2-DS01146B
© 2009 Microchip Technology Inc.
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #1Measuring the Period of a
Square Wave
TIP #2Measuring the Period of a
Square Wave with Averaging
Figure 1-1: Period
Figure 2-1: Period Measurement
16 x T
T
t1
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 Tmax(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).
T
t2
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 Tmax(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).
d) Shift value obtained in step 4.a right four
times to divide by 16 – this result is the
period (T).
Note 1:Tmax is the maximum pulse period
that will occur.
Note 1:Tmax is the maximum pulse period
that will occur.
c) Clear Timer1 flag if set.
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.
DS01146B-Page 3-3
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #3Measuring Pulse Width
TIP #4Measuring Duty Cycle
Figure 3-1: Pulse Width
Figure 4-1: Duty Cycle
T
W
t1
W
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 Wmax 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).
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 Tmax(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:Tmax is the maximum pulse period
that will occur.
5. When the CCP interrupt occurs again,
subtract saved value (t1) from current
captured value (t2) – this result is the pulse
width (W).
6. 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.
Page 3-4-DS01146B
© 2009 Microchip Technology Inc.
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #5Measuring 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).
W
Slotted
Wheel
Front View
Figure 5-3: Low RPM
T
Figure 5-1: Optical Encoder
IR LED
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.
IR Sensor
i e View
Figure 5-4: High RPM
Figure 5-2: Hall Effect Sensor
Magnet
W
Wheel
T
Magnet
Hall effect
Sensor
Front View
© 2009 Microchip Technology Inc.
i e View
DS01146B-Page 3-5
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #6Measuring 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-2: Signal Comparison
Analog
Input
VTHR
Figure 6-1 shows an example circuit using the
peripherals of the PIC16F684.
Figure 6-1: Circuit
time
VSENSE
VTHR
R2
Analog
Input
VREF
R1
R3
R4
PIC16F684
VSENSE
VTHR
time
+
-
VOUT
CCP1
VOUT
Comparator
(on-board PIC16F684)
time
R3 and R4 set the threshold voltage for the
comparator. When the analog input reaches
the threshold voltage, Vout will toggle from
low to high. R1 and R2 provide hysteresis to
insure that small changes in the analog input
won’t cause jitter in the circuit. Figure 6-2
demonstrates the effect of hysteresis on the
input. Look specifically at what Vsense does
when the analog input reaches the threshold
voltage.
Page 3-6-DS01146B
The CCP module, configured in Capture mode,
can time the length between the rising edges of
the comparator output (Vout.) This is the period
of the analog input, provided the analog signal
reaches Vthr during every period.
© 2009 Microchip Technology Inc.
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
“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.
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.)
© 2009 Microchip Technology Inc.
DS01146B-Page 3-7
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #7Periodic 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.
Step #2: Calculate CCPR1 (CCPR1L and
CCPR1H) to shorten the time-out to
exactly 0.2 seconds
a)CCPR1 = Interval Time/(Tosc*4*prescaler) =
0.2/(125 ns*4*8) = 5000 = 0xC350
b)Therefore, CCPR1L = 0x50, and
CCPR1H = 0xC3
Step #3: 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 =
b‘00001010’). Timer 1 must also
be cleared manually during the
CCP interrupt.
c) A prescaler of 8 will cause an overflow at a
time greater than 0.2 seconds.
8 x 32.8 ms = 0.25s
Page 3-8-DS01146B
© 2009 Microchip Technology Inc.
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #8Modulation 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-4: Variable Pulse-width Modulation
TE
TE
TE
TE
TE
Logic
‘0’
Figure 8-1: Pulse-width Modulation
TE
TE
TBP
TBP
Logic
‘1’
TBP
Logic
‘0’
TBP
Transition Low
to High
Logic
‘1’
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.
TBP
Figure 8-2: Manchester
TE
Transition High
to Low
TE
Te is the basic timing element in each
modulation format and will vary based on the
desired baud rate.
Logic
‘0’
Logic
‘1’
TBP
Figure 8-3: Pulse Position Modulation
TE
TE
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).
TE
Logic
‘0’
Logic
‘1’
TBP
© 2009 Microchip Technology Inc.
DS01146B-Page 3-9
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.
Figure 10-1: 16-Bit Resolution PWM
Timer1 Interrupt:
Set CCPx pin
CCPx Interrupt:
Clear CCPx pin
1. Configure CCPx to clear output (CCPx pin)
on match in Compare mode (CCPxCON
<CCPSM3:CCPxM0>).
2. Enable the Timer1 interrupt.
Table 9-1: Tasks
Task
TIP #1016-Bit Resolution PWM
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”.
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
Fpwm = Fosc/(65536*4*prescaler)
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.
Page 3-10-DS01146B
© 2009 Microchip Technology Inc.
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #11 Sequential ADC Reader
Figure 11-1: Timeline
Read AN0
Read AN1
Read AN2
Read AN0
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
Time
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.
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.
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.
© 2009 Microchip Technology Inc.
DS01146B-Page 3-11
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #12Repetitive 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
Figure 12-2: Transposed Waveform
Key
First Pass
Second Pass
Third Pass
Fourth Pass
Volts
IV
Time
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
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.
Page 3-12-DS01146B
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.
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 Vrms
VMAX
DC = 10%
VRMS
T
VRMS
DC = 80%
Equation 12-1 shows the relation between Vrms
and Vmax.
Equation 12-1: Relation Between Vrms and Vmax
Vrms = DCxVmax
© 2009 Microchip Technology Inc.
DS01146B-Page 3-13
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #13Deciding on PWM Frequency
In general, PWM frequency is application
dependent although two general rules-of-thumb
hold regarding frequency in all applications.
They are:
TIP #14Unidirectional Brushed DC
Motor Control Using CCP
Figure 14-1: Brushed DC (BDC) Motor
Control Circuit
Place on
motor
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.
VCC
22 pF
Motor
22 pF
PIC16F628
CCP1
CCP1
EMI/RFI
Suppression
100Ω
10 kΩ
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).
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.
LED and Light Bulbs
a)CCPR1L:CCP1CON<5:4> =
DutyCycle*0x3FF = 0x1FF
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.
Page 3-14-DS01146B
Step #1: Choose Timer2 Prescaler
a)Fpwm = 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/(Fpwm*4*prescaler) – 1 = 249
Step #3: Determine CCPR1L and
CCP1CON<5:4>
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.
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #15Bidirectional Brushed DC
Motor Control Using ECCP
Figure 15-1: Full-Bridge BDC Drive Circuit
VCC
P1A
10 kΩ
10 pF
TC428
10 pF
P1B
10 kΩ
TC428
Motor
VCC
P1C
10 kΩ
TC428
10 pF
TC428
© 2009 Microchip Technology Inc.
The following table shows the relation between
the states of operation, the states of the ECCP
pins and the ECCP Configuration register.
State
10 pF
P1D
10 kΩ
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.
P1A
P1B
P1C
tri-state tri-state
P1D
CCP1CON
mod
‘b01xx1100’
Forward
1
Reverse
tri-state
Coast
tri-state tri-state tri-state tri-state
N/A
Brake
tri-state
N/A
mod
1
1
1
tri-state ‘b11xx1100’
tri-state
Legend:‘1’ = high, ‘0’ = low, mod = modulated, tri-state =
pin configured as input
DS01146B-Page 3-15
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #16Generating an Analog Output
Figure 16-1: Low-Pass Filter
R and C are chosen based on the following
equation:
Equation 16-2
PIC16F684
RC = 1/(2pFbw)
Op Amp
CCP1
+
R
C
-
Analog
Out
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
Att(dB = – 10*log[1+(2pFpwmRC)2]
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 (Fpwm) should be
significantly higher than the bandwidth (Fbw) of
the desired analog signal. Equation 16-1 shows
this relation.
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.
Equation 16-1
Fpwm = K*Fbw
Where harmonics decrease as K increases
Page 3-16-DS01146B
© 2009 Microchip Technology Inc.
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #17Boost Power Supply
Figure 17-1: Boost Power Supply Circuit
PIC16F684
CCP1
AN0
VCC
C1
10 µF
VIN
R3 Q1
10 kΩ
L1
680 µH
VOUT
D1
R1
4.7 kΩ
C2
47 µF
RL
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 Iout is the
maximum load current.
Equation 17-2
L =
Feedback
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 Vcc 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. Vout is related to Vin 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
Vout
Vin
=
1
1-D
Vin (1 - D) DT
2 Iout
The value for L is chosen arbitrarily to satisfy
this equation given Iout, 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
Iripple =
Vin DT
L
Iripple can not exceed the saturation current for
the inductor. If the value for L does produce a
ripple current greater than Isat, 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.
© 2009 Microchip Technology Inc.
DS01146B-Page 3-17
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #18Varying 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.
TIP #19Generating 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
Figure 18-1: LED Drive
OSC2
PIC16F684
200Ω
RC3/CCP1
7.680 MHz
OSC1
CCP1
R1
270Ω
High-Pass Filter
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.
Page 3-18-DS01146B
120 VAC
0.1 µF
X2 Rated
+5 VDC
50Ω
1 MΩ
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.
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
COMBINATION CAPTURE AND
COMPARE TIPS
Auto-baud Routine Implementation:
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 #20RS-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
0
0
0
0
LSB
© 2009 Microchip Technology Inc.
0
0
0
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.
Stop
1 Bit
MSB
DS01146B-Page 3-19
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
Example 20-1: Transmit Routine
TxRountine
MOVLW 8
MOVWF
BCF
counter
TxLine
TxLoop
CALL
RRF
;preload bit counter
;with 8
;line initially high,
;toggle low for START
;bit
DelayTb
;wait Tb (bit period)
RxByte,f ;rotate LSB first into
;the Carry flag
BTFSS STATUS,C ;Tx line state equals
;state of Carry flag
BCF
TxLine
BTFSC STATUS,C
BSF
TxLine
DECFSZ Counter,f ;Repeat 8 times
GOTO
TxLoop
CALL
Delay Tb ;Delay Tb before
;sending STOP bit
BSF
TxLine
;send STOP bit
Example 20-2: Receive Routine
RxRoutine
BTFSC RxLine
GOTO
MOVLW
RxRoutine
8
MOVWF
CALL
Counter
Delay1HalfTb;delay 1/2 Tb here
;plus Tb in RxLoop
;in order to sample
;at the right time
RxLoop
CALL
DelayTb
BTFSS
RxLine
BCF
BTFSC
BSF
BTFSC
BSF
RRF
STATUS,C
RxLine
STATUS,C
RxLine
STATUS,C
RxByte,f
DECFSZ Counter,f
GOTO
RxLoop
Page 3-20-DS01146B
;wait for receive
;line to go low
;initialize bit
;counter to 8
;wait Tb (bit
;period)
;Carry flag state
;equals Rx line
;state
;Rotate LSB first
;into receive type
;Repeat 8 times
© 2009 Microchip Technology Inc.
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
TIP #21Dual-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
Integrator
-
-VREF
Comparator
(on-board PIC16F684)
+
VIN
+
-
PIC16F684
CCP1
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 Vref to Vin.
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 Vin to
Vref 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 Vin using Equation 21-1.
Dual-slope A/D conversion works by integrating
the input signal (Vin) for a fixed time (T1). The
input is then switched to a negative reference
(-Vref) and integrated until the integrator output
is zero (T2). Vin is a function of Vref and the
ratio of T2 to T1.
Equation 21-1
Vin = Vref
T2
T1
Figure 21-2: V vs. Time
V
Integrator output
with VIN input
Integrator output
with VREF input
VIN
T1
T2
VIN
T1
T2
Time
© 2009 Microchip Technology Inc.
DS01146B-Page 3-21
PIC® Microcontroller CCP and ECCP Tips ‘n Tricks
NOTES:
Page 3-22-DS01146B
© 2009 Microchip Technology Inc.
PIC® Microcontroller Comparator Tips ‘n Tricks
CHAPTER 4
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
© 2009 Microchip Technology Inc.
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 lowcost 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.
DS01146B-Page 4-1
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #1Low 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
+
R3
R4
VBATT
R3
R1
Comparator
+
D1
Low Battery
R2
Enable
Comparator will trip when Vbatt = 3V: R1 = 33k,
R2 = 10k and R3 = 470Ω.
VDD
VBATT
Figure 1-2: Unregulated Supply
Low Battery
In Figure 1-2, resistor R3 is chosen to bias
diode D1 above its forward voltage when Vbatt
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.
R2
Enable
The comparator will trip when the battery
voltage, Vbatt = 5.7V: R1 = 33k, R2 = 10k,
R3 = 39k, R4 = 10k, Vdd = 5V.
In Figure 1-1, resistors R1 and R2 are chosen
to place the voltage at the non-inverting input
at approximately 25% of Vdd. R3 and R4
are chosen to set the inverting input voltage
equal to the non-inverting input voltage when
the battery voltage is equal to the minimum
operating voltage for the system.
Page 4-2-DS01146B
© 2009 Microchip Technology Inc.
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #2Faster 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
XORWF CMCON,w
ANDLW COUTMASK
BTFSC STATUS,Z
RETLW 0
MOVF CMCON,w
ANDLW COUTMASK
MOVWF hold
IORLW CHNGBIT
RETURN
;get old Cout
;compare to new Cout
;if = return "no change"
;if not =, get new Cout
;remove all other bits
;store in holding var.
;add change flag
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.
© 2009 Microchip Technology Inc.
Example 2-2
Test
BTFSS
RETLW
BTFSS
RETLW
PIR1,CMIF
0
CMCON,COUT
CHNGBIT
;test comparator flag
;if clear, return a 0
;test Cout
;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
RETLW
MOVLW
XORWF
BTFSS
RETLW
CMCON,COUT
0
CINVBIT
CMCON,f
CMCON,CINV
CHNGFLAG
;test Cout
;if clear, return 0
;if set, invert Cout
;forces Cout to 0
;test Cout polarity
;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.
DS01146B-Page 4-3
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #3Hysteresis
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
R3
R1
R2
To calculate the resistor values required, first
determine the high and low threshold values
which will prevent chatter (Vth and Vtl). Using
Vth and Vtl, the average threshold voltage can
be calculated using the equation.
Equation 3-1
Vavg =
Vavg = Vdd * R2
R1 + R2
Equation 3-3
Req = R1 * R2
R1 + R2
Then, determine the feedback divider ratio Dr,
using Equation 3-4.
Equation 3-4
Dr = (Vth - Vtl)
Vdd
Finally, calculate the feedback resistor R3 using
Equation 3-5.
Equation 3-5
R3 = Req [ (
Vdd * Vtl
Vdd - Vth + Vtl
Next, choose resistor values that satisfy
Equation 3-2 and calculate the equivalent
resistance using Equation 3-3.
Page 4-4-DS01146B
Equation 3-2
Output
+
VDD
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 MW,
can produce voltage offsets at the
non-inverting input due to the
comparator’s input bias current.
1
Dr
) - 1]
Example:
•A Vdd = 5.0V, Vh = 3.0V and Vl = 2.5V
•Vavg = 2.77V
•R = 8.2k and R2 = 10k, gives a Vavg = 2.75V
•Req = 4.5k
•Dr = .1
•R3 = 39k (40.5 calculated)
•Vhact = 2.98V
•Vlact = 2.46V
© 2009 Microchip Technology Inc.
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #4Pulse 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.
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
VDD
VINPUT
Trigger
Level
+
COUT
Timer
Clock
DO
TIG
Timer1
T1CKI
Figure 4-1: Comparator with Timer1 and T1G
VDD
VINPUT
Trigger
Level
-
COUT
+
© 2009 Microchip Technology Inc.
TIG
Timer1
DS01146B-Page 4-5
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #5Window 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
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 MW to
prevent offset voltages due to the
input bias currents of the comparator.
Equation 5-1
VDD
Vth-hi =
R1
Equation 5-2
+
High Limit
Vth-lo =
Input
R2
Vdd * R3
R1 + R2 + R3
Example:
+
Low Limit
-
R3
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.
Page 4-6-DS01146B
Vdd * (R3 +R2)
R1 + R2 + R3
•Vdd = 5.0V, Vth = 2.5V, Vtl = 2.0V
•R1 = 12k, R2 = 2.7k, R3 = 10k
•Vth (actual) = 2.57V, Vtl (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 kW, 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.
© 2009 Microchip Technology Inc.
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #6Data 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.
Figure 6-1: Data Slicer
VDD
R2
Comparator
-
Input
R1
+
R3
Output
C1
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.
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.
© 2009 Microchip Technology Inc.
DS01146B-Page 4-7
PIC® Microcontroller Comparator Tips ‘n Tricks
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, Vhi and Vlo, 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.
Page 4-8-DS01146B
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
VDD
C1
VDD
R2
V1
R1
D1
-
R3
V2
+
C2
Input
R5
Output
Comparator
R4
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
Tpulse =
R2 * C1 * In(Vth/Vtl)
4
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:
•Vdd = 5V, Vth = 3.0V, Vtl = 2.5V
•From Tip #3, R4 = 1k, R5 = 1.5k and R3 = 12k
•Tpulse = Ims, C1 = .1 mF and R2 = 15k
•D1 is a 1N4148, R1 = 220W and C2 = 150 pF
© 2009 Microchip Technology Inc.
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #8Multi-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.
To design a multi-vibrator, first design the
hysteresis feedback path using the procedure in
Tip #3. Be careful to choose threshold voltages
(Vth and Vtl) that are evenly spaced within the
common mode range of the comparator and
centered on Vdd/2. Then use Vdd and Vtl to
calculate values for RT and CT that will result in
the desired oscillation frequency Fosc. Equation
8-1 defines the relationship between RT, CT,
Vth, Vtl and Fosc.
Equation 8-1
Fosc =
1
2 * RT * CT * In(Vth/Vtl)
Example:
•Vdd = 5V, Vth = 3.333, Vtl = 1.666V
•R1, to R2, to R3 = 10k
•Rt = 15 kHz, Ct = .1 mF for Fosc = 480 Hz
Figure 8-1: Multi-Vibrator Circuit
CT
RT
-
VDD
+
R1
R2
Output
Comparator
R3
© 2009 Microchip Technology Inc.
DS01146B-Page 4-9
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #9Multi-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
D1
CT
Equation 9-1
Fosc =
1
RT * CT * In(Vth/Vtl)
This assumes that the dynamic on resistance of
D1 is much less than RT.
Example:
•Vdd = 5V, Vth = 1.666V and Vth = 3.333V
•R1, R2 and R3 = 10k
•Rt = 15k, Ct = .1 mF for a Fosc = 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
Output
Fosc =
Icld
C (Vth - Vtl)
RT
-
VDD
Then use Vth and Vtl to calculate values for RT
and CT that will result in the desired oscillation
frequency Fosc. Equation 9-1 defines the
relationship between RT, CT, Vth, Vtl and Fosc.
Comparator
Figure 9-2: Alternate Ramp Waveform
Multi-Vibrator Using a CLD
+
R1
D1
R2
R3
CT
CLD
Comparator
-
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 (Vth and Vtl) that
are evenly spaced within the common mode
range of the comparator.
Page 4-10-DS01146B
VDD
Output
+
R1
R2
R3
© 2009 Microchip Technology Inc.
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #10Capacitive 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 Vdd through
D1 and into C1. When the output of the multivibrator goes high, D1 is reverse biased and the
charge current stops. The voltage across C1 is
added to the output voltage of the multi-vibrator,
creating a voltage at the positive terminal of C1
which is 2 x Vdd. This voltage forward biases D2
and the charge in C1 is shared with C2. When
the output of the multi-vibrator goes low again,
the cycle starts over.
Figure 10-2: Equivalent Output Model
2 x VDD
VOUT
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
Figure 10-1: Capacitive Voltage Doubler
CT
- Comparator
VDD
+
R1
R2
Rout =
VDD
RT
D1
C1
+
D2
VOLT
+
C2
R3
Note:The output voltage of a capacitive
double is unregulated and will sag
with increasing load current.
Typically, the output is modeled as a
voltage source with a series
resistance (see Figure 10-2).
ROUT
1
Fswitch * C1
Note:Rout will be slightly higher due to
the dynamic resistance of the diodes.
The equivalent series resistance or
ESR, of the capacitors and the
output resistance of the comparator.
See the TC7660 data sheet for a
more complete description.
Once the switching frequency is determined,
design a square-wave multi-vibrator as
described in Tip #8.
Finally, select diodes D1 and D2 for their current
rating and set C2 equal to C1.
Example:
From Tip #8, the values are modified for a Fosc
of 4.8 kHz.
•C1 and C2 = 10 mF
•Rout = 21W
© 2009 Microchip Technology Inc.
DS01146B-Page 4-11
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #11 PWM Generator
Figure 11-2: PWM Circuit
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
Input
Output
Time
Time
Time
Comparator
-
Output
+
Input
V1
D1
CT
CLD
-
VDD
Comparator
+
R3
R1
R2
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.
Page 4-12-DS01146B
© 2009 Microchip Technology Inc.
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #12Making 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).
Comparator
R3
+
-
R2
Output
C2
R1
C1
VDD
+
Comparator
R3
-
Input
A value for C1 can then be determined using
Equation 12-3. The corner frequency should be
the same as Equation 12-3.
Fcorner =
10K
R2
Output
C2
1
2 * p * (R1 II R2) * C2
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
R1
C1
1
2 * p * R3 * C2
Equation 12-3
Figure 12-2: Inverting Amplifier
10K
Equation 12-2
Fcorner =
Figure 12-1: Non-Inverting Amplifier
Input
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.
Gain =
R1
R2
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).
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.
Equation 12-1
Example:
Gain =
R1 + R2
R2
© 2009 Microchip Technology Inc.
•For C2 will set the corner F
•Gain = 6.156, R1 = R3 = 19.8k
•R2 = 3.84k, C1 = .047 mF, Fcorner = 171 Hz
•C2 = .22 mF
DS01146B-Page 4-13
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #13PWM 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
VDD
Drive
Level
Comparator
R3
P ch
MOSFET
+
R2
C1
Load Current
Drive Level
Ripple Current
Time
To design a PWM high current driver, first
determine a switching speed (Fswx) 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
Load
Fswx =
R1
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.
Page 4-14-DS01146B
Figure 13-1: Current Through the Load
2
R2 * C1
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
L =
Vdd - Vload
Iripple * Fswx * 2
Finally, choose a value for R1 that will produce
a feedback ripple voltage of 100 mV for the
maximum ripple current Iripple.
Example:
•Fswx = 10 kHz, R2 = 22k, C1 = .01 mF
•Iripple = 100 mA, Vdd = 12V, Vl = 3.5V
•L = 4.25 mH
© 2009 Microchip Technology Inc.
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #14Delta-Sigma ADC
This tip describes the creation of a hardware/
software-based Delta-Sigma ADC. A DeltaSigma 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 Vdd/2 reference for
the circuit (see Figure 14-1).
Figure 14-1: Delta-Sigma Modulator
Input
R1
R2
-
C1
Comparator
+
VDD
R3
Software
Data
R4
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 Vdd.
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
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.
© 2009 Microchip Technology Inc.
DS01146B-Page 4-15
PIC® Microcontroller Comparator Tips ‘n Tricks
TIP #15Level Shifter
TIP #16Logic: Inverter
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
(Vin/2). The non-inverting input is then used for
the circuit input. When the input is below the
Vin/2 threshold, the output is low. When the
input is above Vin/2, then the output is high.
Values for R1 and R2 are not critical, though
their ratio should result in a threshold voltage
Vin/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.
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.
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
R1
+
Values for R1 and R2 are not critical, though
they must be equal to set the threshold at
Vdd/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.
VDD
A
The non-inverting input is biased to the center
of the input voltage range, typically Vdd/2. The
inverting input is then used for the circuit input.
When the input is below Vdd/2, the output is
high. When the input is above Vdd/2, then the
output is low.
Y
Figure 16-1: Inverter
VDD
R2
R1
+
Example:
Page 4-16-DS01146B
-
•Vin = 0 - 2V, Vin/2 = 1V, Vdd = 5V
•R2 = 10k, R3 = 3.9k
A
Y
R2
© 2009 Microchip Technology Inc.
PIC® Microcontroller Comparator Tips ‘n Tricks
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 Vdd 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.
R3
A
R4
B
VDD
-
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 Vdd 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
Vdd.
Figure 17-1: AND Gate
+
TIP #17Logic: AND/NAND Gate
R1
Y
R2
Figure 17-2: NAND Gate
R3
A
R4
B
-
VDD
+
R1
Y
R2
Example:
•Vdd = 5V, R3 = R4 = 10k
•R1 = 5.1k, R2 = 10k
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.
© 2009 Microchip Technology Inc.
DS01146B-Page 4-17
PIC® Microcontroller Comparator Tips ‘n Tricks
Resistors R1 and R2 drive the non-inverting
input of the comparator with 1/3 Vdd. 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 Vdd 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
Vdd 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.
R3
A
R4
B
VDD
-
This tip shows the use of the comparator to
implement an OR gate, and its complement, the
NOR gate.
Figure 18-1: OR Gate
+
TIP #18Logic: OR/NOR Gate
R1
Y
R2
Figure 18-2: NOR Gate
R3
A
R4
B
-
VDD
+
R1
Y
R2
Example:
•Vdd = 5V, R3 = R4 = 10k
•R1 = 10k, R2 = 5.1k
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.
Page 4-18-DS01146B
© 2009 Microchip Technology Inc.
PIC® Microcontroller Comparator Tips ‘n Tricks
The operation is best described in three
sections:
A
B
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 Vdd (the
average of a Vdd input and Gnd). 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.
R2
Comparator
Y
R3
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 Vdd and the non-inverting input
is equal to 2/3 Vdd (the average of Vdd inputs
and Gnd). This combination also results in a
low output.
R1
-
This tip shows the use of the comparator to
implement an XOR gate and its complement the
XNOR gate.
Figure 19-1: XOR Gate
+
TIP #19Logic: XOR/XNOR Gate
R4
D1
VDD
D2
Figure 19-2: XNOR Gate
A
B
R1
-
R2
Comparator
Y
+
R3
D1
R4
VDD
D2
Example:
•D1 = D2, = 1N4148
•R4 = 10k, R1 = R2 = R3 = 5.1k
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
Vdd 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.
© 2009 Microchip Technology Inc.
DS01146B-Page 4-19
PIC® Microcontroller Comparator Tips ‘n Tricks
The inverting and non-inverting inputs are
biases at Vdd/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
Vdd/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.
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 Vdd/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
VDD
VDD
R1
R3
SET
R5
RESET
-
This tip shows the use of the comparator to
implement a Set/Reset Flip Flop.
While the circuit is fairly simple, there are a few
requirements for correct operation:
+
TIP #20Logic: Set/Reset Flip Flop
R2
Q
R4
Example:
•Diodes = 1N4148
•R1 = R2 = R3 = R4 = 10k
•R5 = 10k
Page 4-20-DS01146B
© 2009 Microchip Technology Inc.
DC Motor Control Tips ‘n Tricks
CHAPTER 5
DC Motor Control
Tips ‘n Tricks
Table Of Contents
TIPS ‘N TRICKS INTRODUCTION
TIP #1: Brushed DC Motor Drive Circuits........
TIP #2: Brushless DC Motor Drive Circuits......
TIP #3: Stepper Motor Drive Circuits...............
TIP #4: Drive Software.....................................
TIP #5: Writing a PWM Value to the CCP
Registers with a Mid-Range
PIC® MCU............................................
TIP #6: Current Sensing..................................
TIP #7: Position/Speed Sensing......................
TIPS ‘N TRICKS INTRODUCTION
5-2
5-3
5-4
5-6
5-7
5-8
5-9
Application Note References................................ 5-11
Motor Control Development Tools........................ 5-11
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).
© 2009 Microchip Technology Inc.
DS01146B-Page 5-1
DC Motor Control Tips ‘n Tricks
TIP #1Brushed DC Motor Drive
Circuits
Figure 1-3: H-Bridge Drive
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.
V+
V+
D
A
M
Figure 1-1: High Side Drive
V+
PIC®
Microcontroller
C
B
Digital
Output
A-D are digital outputs from a PIC® MCU.
MOSFET
Driver
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
V+
PIC®
Microcontroller
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)
M
Digital
Output
MOSFET
Driver
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.
Page 5-2-DS01146B
© 2009 Microchip Technology Inc.
DC Motor Control Tips ‘n Tricks
TIP #2Brushless 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.
Figure 2-1: 3 Phase Brushless DC Motor
Control
V
V
OA
OC
V
OE
A
B
C
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.
OB
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.
OA-OF are digital outputs from a PIC® MCU.
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.
© 2009 Microchip Technology Inc.
OD
OF
B
A
Motor
C
Figure 2-2: Back EMF Sensing (Sensorless
Motor)
PIC® MCU or dsPIC® DSC
A
ADC
B
Low Pass
Filter
C
Analog
MUX
DS01146B-Page 5-3
DC Motor Control Tips ‘n Tricks
Figure 2-3: Quadrature Decoder (Sensor Motor)
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.
PIC® MCU or dsPIC® DSC
Digital
Inputs
Digital
Outputs
Drive
Circuit
A
B
Motor
C
Hall
Effect
Motor
Position
Sensor
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)
Page 5-4-DS01146B
TIP #3Stepper Motor Drive Circuits
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.
DC Motor Control Tips ‘n Tricks
Figure 3-1: 4 and 5 Wire Stepper Motors
Figure 3-4: Bipolar Motor (4 Half-Bridges)
V
Unipolar 5 Wire
A
C
B
D
Bipolar 4 Wire
Figure 3-2: 6 and 8 Wire Stepper Motors
Short for
Unipolar
V
Individual coils
wire anyway
appropriate
8 Wire
Unipolar and Bipolar
6 Wire
Figure 3-3: Unipolar Motor (4 Low Side
Switches)
Motor
V
Motor
E
G
F
H
V
V+
A-H are digital outputs from a PIC® MCU
or dsPIC® DSC.
01
02
03
04
01-04 are outputs from a PIC® MCU or dsPIC® DSC.
© 2009 Microchip Technology Inc.
DS01146B-Page 5-5
DC Motor Control Tips ‘n Tricks
TIP #4Drive 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
MOVLW A
MOVWF pwm
endm
update_PWM macro
;sets the pwm
;setpoint to the
;value A
;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
Page 5-6-DS01146B
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
MOVF
SUBWF
RLF
MOVF
SUBWF
RLF
MOVF
SUBWF
RLF
MOVF
SUBWF
RLF
MOVF
SUBWF
RLF
MOVF
SUBWF
RLF
MOVF
SUBWF
RLF
MOVF
SUBWF
RLF
MOVWF
INCF
endm
;peforms one
;update of all 8
;PWM signals
;all PWM signals
;must be on the
;same port
pwm_counter,w
pwm0,w
output,f
pwm_counter,w
pwm1,w
output,f
pwm_counter,w
pwm2,w
output,f
pwm_counter,w
pwm3,w
output,f
pwm_counter,w
pwm4,w
output,f
pwm_counter,w
pwm5,w
output,f
pwm_counter,w
pwm6,w
output,f
pwm_counter,w
pwm7,w
output,w
PORTC
pwm_counter,f
© 2009 Microchip Technology Inc.
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
setPeriod
macro a
RRF
a,w
MOVWF
RRF
ANDLW
IORLW
MOVWF
MOVF
MOVWF
pwm_tmp
pwm_tmp,w
0x30
0x0F
CCP1CON
a+1,w
CCPR1L
;this variable must be
;allocated someplace
;a is 2 SFR’s in
;Low:High arrangement
;the 10 MSb’s are the
;desired PWM value
;This macro will
;change w
© 2009 Microchip Technology Inc.
Example 5-2: Right Justified 16-Bit Macro
pwm_tmp
equ xxx
setPeriod
macro a
SWAPF
a,w
ANDLW
IORLW
MOVWF
RLF
IORLW
MOVWF
RRF
RRF
MOVWF
0x30
0x0F
CCP1CON
a,w
0x0F
pwm_tmp
pwm_tmp,f
pwm_tmp,w
CCPR1L
;this variable must be
;allocated someplace
;a is 2 bytes in
;Low:High arrangement
;the 10 LSb’s are the
;desired PWM value
;This macro will
;change w
Example 5-3: 8-Bit Macro
pwm_tmp
equ xxx
setPeriod
SWAPF
macro a
a,w
ANDLW
IORLW
MOVWF
RRF
MOVWF
RRF
MOVWF
0x30
0x0F
CCP1CON
a,w
pwm_tmp
pwm_tmp,w
CCPR1L
;this variable must be
;allocated someplace
;a is 1 SFR
;This macro will
;change w
DS01146B-Page 5-7
DC Motor Control Tips ‘n Tricks
VSUPPLY
M
CCP
PIC MCU
or
dsPIC® DSC
®
MOSFET
Driver
MCP
ADC
Current
Sensor
Resistor
-
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-2: Resistive Low Side Current
Sensing
+
TIP #6Current Sensing
Current Sensor
Amplifier
Figure 6-1: Resistive High Side Current
Sensing
Current Sensor
Resistor
VSUPPLY
V+
ADC
PIC® MCU
or
dsPIC® DSC
RS+
RS-
MAX4172
High Side
Current
Sensor
Amplifier
M
1k
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
Motor Supply
MOSFET
Driver
VDD
Ferrite
Toroid
ADC
PIC® MCU
or
dsPIC® DSC
Hall
Effect
Sensor
M
CCP
Page 5-8-DS01146B
© 2009 Microchip Technology Inc.
DC Motor Control Tips ‘n Tricks
TIP #7Position/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
Motor Supply
VDD
Q1
CCP
PIC® MCU
or
dsPIC® DSC
ADC
Back EMF Monitor(1)
M
Note 1: If motor voltage is greater than VDD, an
attenuator will be required. Sample back
EMF while Q1 is off.
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.
© 2009 Microchip Technology Inc.
DS01146B-Page 5-9
DC Motor Control Tips ‘n Tricks
Figure 7-2: Optical Speed/Direction/Position
Sensing
VDD
A
VDD
M
Drive
B
Older Methods of Motor Sensing
Encoder Wheel
on Motor Shaft
LED
Photo
Transistor
A
PIC® MCU
or
dsPIC® DSC
B
Encoder Wheel
A
B forward
B reverse
Note: Frequency of one signal provides RPM of motor. Pulse count
provides motor position. A-B phase provides motor direction.
Page 5-10-DS01146B
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.
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.
DC Motor Control Tips ‘n Tricks
Application Note References
Motor Control Development Tools
•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.
•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.
© 2009 Microchip Technology Inc.
DS01146B-Page 5-11
DC Motor Control Tips ‘n Tricks
NOTES:
Page 5-12-DS01146B
© 2009 Microchip Technology Inc.
LCD PIC® Microcontroller Tips ‘n Tricks
CHAPTER 6
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
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.
Application Note References................................ 6-11
© 2009 Microchip Technology Inc.
DS01146B-Page 6-1
LCD PIC® Microcontroller Tips ‘n Tricks
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.
Page 6-2-DS01146B
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 #2LCD PIC® MCU Segment/
Pixel Table
Table 2-1: Segment Matrix Table
Maximum Number of Segments/Pixels
Multiplex
PIC18F8X90
Commons PIC16F913/ PIC16F914/ PIC16F946 PIC18F6X90
916
917
(PIC18F6XJ90) (PIC18F8XJ90)
Bias
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).
© 2009 Microchip Technology Inc.
LCD PIC® Microcontroller Tips ‘n Tricks
TIP #3Resistor Ladder for Low
Current
Bias voltages are generated by using an
external resistor ladder. Since the resistor
ladder is connected between Vdd and Vss,
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 Vdd = 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
VDD
VLCD3
SEGn
CPIXEL (n x m)
VLCD1
COMm
R
VSS
VLCD0
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 Vlcd3 and Vlcd0,
so we look at the two cases where it is nonzero, Vlcd2 and Vlcd1.
© 2009 Microchip Technology Inc.
RTH
VTH
+
-
RSW
CPIXEL
RCOM
Figure 3-3: LCD Circuit Resistance Estimate
VLCD2
R
Figure 3-2: Simplified LCD Circuit
The Thevenin voltage is equal to either 2/3 Vdd,
or 1/3 Vdd, 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.
LCD PIC® MCU
R
The circuit can be simplified as shown in Figure
3-2. Rsw is the resistance of the segment
multiplex switch; Rcom is the resistance of the
common multiplex switch.
RTH = (2R * R)/(2R + R)
RTH = 2R2/3R
RTH = 2R/3
RTOTAL = RTH + RSW + RCOM
RSW = 4.7K
RCOM = 0.4K
VTH
+
-
CPIXEL
As you can see, we can model the drive of a
single pixel as an RC circuit, where the voltage
switches from 0V to Vlcd2, 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 Vth will
depend on the capacitance of the pixel and the
total resistance, of which the resistor ladder
Thevenin resistance forms the most significant
part.
DS01146B-Page 6-3
LCD PIC® Microcontroller Tips ‘n Tricks
Figure 3-4: Voltage Change Across Pixel
RTOTAL
VTH
VPIXEL
+
-
CPIXEL
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 step response of the voltage across a pixel
is subject to the following equation:
Equation 3-1
Vpixel = Vth (1 - e-t/rc)
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.
Rtotal = 100 mS/45 pF = 2.22 mΩ
Rth = 2.2M - 5.1K = 2.2M
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 Vlcd2 and Vlcd1 can
be treated the same as Rtotal. We can then
calculate the value for R that will give us the
correct Thevenin resistance.
Equation 3-4
R = 3 Rth/2 = 3.3M
Figure 3-5: Step Response Diagram
VPIXEL
Now we can calculate the current through the
resistor ladder if we used 3.3 mΩ resistors.
VTH
VPIXEL/VTH = 1 - e -t/RC
98% = 1 - e -t/RC
0.98
VTH
2% = e -t/RC
In (.02) = -t/RC
t = ~ 4 RC
0
Equation 3-5
t = 4 RC t
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
Rladder = 9.9M,
Iladder = 5V/9.9M = 0.5 mA
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.
Cpixel = 1500 pF/cm2
AREApixel = 1 mm * 3 mm = .03 cm2
Cpixel = 45 pF
Page 6-4-DS01146B
© 2009 Microchip Technology Inc.
LCD PIC® Microcontroller Tips ‘n Tricks
TIP #4: Contrast Control with a
Buck Regulator
TIP #5: Contrast Control Using a
Boost Regulator
Contrast control in any of the LCD PIC MCUs is
accomplished by controlling the voltages applied
to the Vlcd 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
Vdds. 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.
In LCD Tip #4, a buck converter was created
using a comparator. This circuit works great
when Vdd 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
Figure 4-1: Voltage Generator with
Resistor Divider
R1
R2
D1
VDD
RA1
RA5
R6
R3
D2
R4
VLCD3
C1
R4
R5
0.6V
R1
C2
C3
VLCD2
LCD
Glass
Q1
C1
Boost
C1
R5
VDD
R2
VLCD1
R6
C2
R3
C2
D3
PIC16F91X
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 Vlcd3 is compared to the internal
voltage reference by dividing the voltage at
Vlcd3 at R4 and R5 and applying the reduced
voltage to the internal comparator. When the
voltage at Vlcd3 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 Vlcd1 and Vlcd2 are steady.
© 2009 Microchip Technology Inc.
R7
PIC16F946/917/916/914/913
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.
DS01146B-Page 6-5
LCD PIC® Microcontroller Tips ‘n Tricks
Figure 5-2: Two Types of Boost Converter
VBAT
VBAT
L1
R8
Q2
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 Vdd. This
allows the voltage at Vlcd to exceed Vdd.
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
Vdd supply. The PWM will then be used to
compensate for variations in the supply voltage.
Figure 6-1: Software Controlled Voltage
Generator
VDD
VDD
AN0
R6
R5
CCP
VLCD3
R1
C1
C2
D1
C3
VLCD2
LCD
Glass
R2
VLCD1
R3
LCD PIC®
MCU
Page 6-6-DS01146B
© 2009 Microchip Technology Inc.
LCD PIC® Microcontroller Tips ‘n Tricks
TIP #7Driving Common Backlights
Figure 7-1: Simple Boost Supply
Any application that operates in a low light
condition requires a backlight. Most low-cost
applications use one of the following backlights:
VDD
L1
1)Electroluminescent (EL)
R1
Q2
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.
© 2009 Microchip Technology Inc.
LED String
To Comparator Input
R2
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 Vdd
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
VDD
LED
String
R1
DS01146B-Page 6-7
LCD PIC® Microcontroller Tips ‘n Tricks
TIP #8In-Circuit Debug (ICD)
TIP #9LCD in Sleep Mode
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.
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.
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.
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.
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.
Table 9-1: Options for LCD in Sleep Mode
Part
PIC16C925/926
PIC16F946/917/
916/914/913
PIC18F6X90
PIC18F8X90
PIC18F6XJ90
PIC18F8XJ90
Fosc/256
T1OSC
Internal RC Oscillator
Fosc/8192
T1OSC/32
LFINTOSC/32
(Fosc/4)/8192
T1OSC
Use in
Sleep?
No
Yes
Yes
No
Yes
Yes
No
Yes
INTRC/32
Yes
LCD Clock Source
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.
Page 6-8-DS01146B
© 2009 Microchip Technology Inc.
LCD PIC® Microcontroller Tips ‘n Tricks
TIP #10How 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.
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.
DS01146B-Page 6-9
LCD PIC® Microcontroller Tips ‘n Tricks
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
TIP #124 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
Update Character 1
Start
Blink Flag
Character 1
Blink
Enable
Character 1
Buffer
Is Blink
flag
set?
Y
Is
Character 1
Blink enable
set?
N
N
Update
Character 1
Pixels
Y
Clear
Character 1
Pixels
LCDDATA
Pixel Bits
Finish
Page 6-10-DS01146B
© 2009 Microchip Technology Inc.
LCD PIC® Microcontroller Tips ‘n Tricks
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).
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
<Vdd/10
–
–
–
–
Vdd/5.2
2
8
C
E
Vdd/4.2
1
7
3
9
Vdd/3
5
0
D
F
Vdd/2
4
A
6
B
5. Perform two successive A/D conversions,
first on AN0, then on AN1.
9. This loop should be repeated about once
every 20 ms or so.
6. Save the conversion results to their respective
variables; for example, RB5_AN0_Result
and RB5_AN1_Result.
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.
- RB0_AN0_Result
denotes key press of 1, 2, 4 or 5
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.
7. There are now 4 variables that represent
a key press in each quadrant of the 4 x 4
keypad:
- 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.
DS01146B-Page 6-11
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.
Page 6-12-DS01146B
© 2009 Microchip Technology Inc.
Intelligent Power Supply Design Tips ‘n Tricks
CHAPTER 7
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
© 2009 Microchip Inc.
TIPS ‘N TRICKS INTRODUCTION
Microchip continues to provide innovative
products that are smaller, faster, easier-touse 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.
DS01146B-Page 7-1
Intelligent Power Supply Design Tips ‘n Tricks
TIP #1Soft-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%.
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
PWM
Figure 1-1: Soft-Start Circuit Schematic
Output Voltage
VDD
100%
0.1 µF
On/Off
Control
Input
V
5
1
GP0
0%
GP1
3
Shutdown
PWM Output
10 kΩ
N.C. X
6
GP3
GP2
4
X N.C.
2
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.
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.
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.
Page 7-2-DS01146B
© 2009 Microchip Inc.
Intelligent Power Supply Design Tips ‘n Tricks
TIP #2A 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
Two conditions must be met in order for the
soft-start sequence to begin:
1. The shutdown pin must be held at Vdd
(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
VDD
0.1 µF
UnderVoltage
Lockout
Shutdown
V1
5
1
GP0/CIN+ GP1
3
PWM Output #1
V2
10 kΩ
6
GP3
GP2
4
2
PWM Output #2
10 kΩ
Note: Assumes SOT-23 packaging.
This design uses the PIC MCU comparator to
implement an under-voltage lockout. The input
on the GP0/Cin+ pin must be above the internal
0.6V reference for soft-start to begin, as shown
in Figure 2-2.
© 2009 Microchip Inc.
PWM1
PWM2
1
2
3
4
5
1. Start-up conditions met
2. Initial delay
3. PWM Ramp #1 complete
4. Between PWM delay
5. PWM #2 complete
Example software is provided for the
PIC10F200 which was taken from TB093,
“Multiple PWM Output Soft-Start Controller for
Switching Power Supplies” (DS91093).
DS01146B-Page 7-3
Intelligent Power Supply Design Tips ‘n Tricks
TIP #3A 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
Table 3-1: Shutdown Pin Logic
Shutdown
A
Shutdown
B
Va > Vb
Low
High
Vb > Va
High
Low
Vb > Internal Reference
High
High
Case
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.
VA
Voltage
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.
VB
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.
Time
Figure 3-2: Example Schematic
VDD
0.1 µF
VA
Resistor
Divider 1
-
VB
Shutdown A
+
Resistor
Divider 2
Control
Software
R1
Shutdown B
R2
Shutdown
Page 7-4-DS01146B
PIC12F629
© 2009 Microchip Inc.
Intelligent Power Supply Design Tips ‘n Tricks
TIP #4Creating 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 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
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.
10 dB/REF 20 dBm
Figure 4-1: Spectrum of Clock Output
Before Dithering
10 dB/REF 20 dBm
Center 1.0 MHz
Span 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.
Center 1.0 MHz
© 2009 Microchip Inc.
Span 1.8 MHz
DS01146B-Page 7-5
Intelligent Power Supply Design Tips ‘n Tricks
TIP #5Using 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
VIN
L1
P C
MC
MCP1630
M1
VEXT
VIN
D1
C1
R2
OSC IN
FB
R1
CS
RSENSE
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.
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 Fosc/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.
2. The voltage at the Feedback (FB) pin is
higher than the reference voltage (Vref).
3. The clock/oscillator source transitions from
low-to-high.
Page 7-6-DS01146B
© 2009 Microchip Inc.
Intelligent Power Supply Design Tips ‘n Tricks
TIP #6Current Limiting Using the
MCP1630
Figure 6-1:MCP1630 High-Speed PWM
VIN
UVLO
S
VIN
FB
VREF
VIN
EA
+
+
0.1 µA
CS
Comp
Equation 6-1
Overtemperature VIN
0.1 µA
OSC IN
VEXT
(1)
Q
100 kΩ
Comp
t
2R R
2.7V Clamp
Imax = (0.9V) / Rsense
GND
Q
R
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.
t
e
0
0
Qn
0
1
1
1
0
0
1
1
1
For high current applications, this method may
be acceptable. When lower current limits are
required, the size of the sense resistor, Rsense,
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
VDD
L1
R1
R2
Note 1: During overtemperature, VEXT driver is high-impedance.
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.
CS Input
+
RSENSE
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
0.9V =
(Vdd - Imax • Rsense) • R2
R1 + R2
Equation 6-2 can be solved to determine the
values of R1 and R2 that provide the desired
current limit.
© 2009 Microchip Inc.
DS01146B-Page 7-7
Intelligent Power Supply Design Tips ‘n Tricks
TIP #7Using a PIC® Microcontroller
for Power Factor Correction
Figure 7-2:Desired and Actual Inductor
Currents
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
L1
+
-
+
-
D1
M1
+
PWM
C1
VBoost
+
C2
The AC voltage is rectified and boosted to
voltages as high as 400 Vdc. 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.
Page 7-8-DS01146B
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.
© 2009 Microchip Inc.
Intelligent Power Supply Design Tips ‘n Tricks
TIP #8Transformerless Power
Supplies
Resistive Power Supply
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
VOUT
L
IIN
D1
5.1V
N
C2
470 µF
IOUT
C1
R1
.47µ 250V
470Ω 1/2W
D2
Figure 8-1 shows the basics for a capacitive
power supply. The Zener diode is reversebiased 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.
Figure 8-2: Resistive Power Supply
L
VOUT
IIN
D1
5.1V
N
R1
R2
1KΩ 5W 1KΩ 5W
C2
IOUT
D2
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).
DS01146B-Page 7-9
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
Q1
Load
AC IN
R1
C2
U1
+
Do
-
Page 7-10-DS01146B
+5V C1
VDD
GP0/C+ GP2/COUT
GP1/C- GP2/MCLR
VSS
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.
Load
R2
Zero Crossing
Detection
© 2009 Microchip Inc.
Intelligent Power Supply Design Tips ‘n Tricks
TIP #10Driving 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
Method 2
Figure 10-2: Schematic
+5V
Figure 10-1: Typical Change Pump
VDD
D1
CLKOUT
CPUMP
D1
FET Driver
D2
VOUT max =
2 * VDD - 2 * VDIODE
D2
CFILTER
U1A
PWM2
+12V
M1
PWM1
C2
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 Cpump. After CLKOUT is high,
D2 is forward biased, moving the charge to
Cfilter. The result is a voltage equal to twice
the Vdd minus two diode drops. This can be
used with a PWM or any other I/O pin that
toggles.
© 2009 Microchip Inc.
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.
C1
L1
U1B
M2
The +5V is used for powering the microcontroller.
Using this arrangement, the FET driver would
have approximately 12 + (5 - Vdiode) - Vdiode
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 - Vdiode) 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 - Vdiode). The
D2 turns on and the voltage supplied to the FET
driver is 12V + (5V - Vdiode) - Vdiode.
DS01146B-Page 7-11
Intelligent Power Supply Design Tips ‘n Tricks
TIP #11 Generating a Reference
Voltage with a PWM Output
R and C are chosen based on the following
equation:
Figure 11-1: Low-Pass Filter
Equation 11-2
RC = 1/(2 • p • Fbw)
Where harmonics decrease as K increases.
MCP6001
CCP1
R
+
C
-
Analog
Out
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
A PWM signal can be used to create a Digitalto-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 (Fpwm) should be
significantly higher than the bandwidth (Fbw) of
the desired analog signal. Equation 11-1 shows
this relation.
Equation 11-1
Fpwm = K • Fbw
Where harmonics decrease as K increases.
Page 7-12-DS01146B
Att(dB) = -10 • log [1 + (2 p • Fpwm • RC) 2]
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).
© 2009 Microchip Inc.
Intelligent Power Supply Design Tips ‘n Tricks
Several of Microchip’s PIC MCUs, such as the
PIC16F684, PIC16F685 and PIC16F690, have
a PWM auto-shutdown feature. When autoshutdown 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
PWM Signal
Shutdown
Event
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.
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
VIN
L1
Internal to PIC® MCU
R1
PWM
Module
Out
-
PWM Auto-Shutdown
Using Auto-Shutdown to Create a
Boost Supply
+
TIP #12Using Auto-Shutdown CCP
Q1
VOUT
D1
C1
R2
R3
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.
DS01146B-Page 7-13
Intelligent Power Supply Design Tips ‘n Tricks
TIP #13Generating 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.
Figure 13-2: Two-Phase Control Signal
Schematic
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.
P1A
PIC® MCU
P1B
Page 7-14-DS01146B
© 2009 Microchip Inc.
Intelligent Power Supply Design Tips ‘n Tricks
TIP #14Brushless DC Fan Speed
Control
There are several methods to control the
speed of a DC brushless fan. The type of fan,
allowable power consumption and the type of
control desired are all factors in choosing the
appropriate type.
Figure 14-1: Low-Side PWM Drive
12V
PWM Drive
Because of this, it is necessary to switch the
high side of the fan in order to control the
speed. The simplest type of speed control is ‘on’
or ‘off’. However, if a higher degree of control is
desired, PWM can be used to vary the speed of
the fan.
For 3-wire fans, the tachometer output will
not be accurate if PWM is used. The sensor
providing the tachometer output on 3-wire fans
is powered from the same supply as the fan
coils, thus using a PWM to control fan speed
will render the fan’s tachometer inaccurate.
One solution is to use a 4-wire fan which
includes both the tachometer output and a drive
input. Figure 14-3 shows a diagram of a 4-wire
fan.
Figure 14-3: Typical 4-Wire Fan
V+
Figure 14-2: High-Side PWM Drive
12V
Drive
12V
PWM Drive
TACH
TACH
GND
Method 1 – Pulse-Width Modulation
As shown in Figure 14-1 and Figure 14-2, a
simple PWM drive may be used to switch a
two-wire fan on and off. While it is possible to
use the circuit in Figure 14-1 without a high-side
MOSFET driver, some manufacturers state that
switching on the low side of the fan will void the
warranty.
© 2009 Microchip Inc.
A 4-wire fan allows speed to be controlled
using PWM via the Drive line. Since power to
the tachometer sensor is not interrupted, it will
continue to output the correct speed.
DS01146B-Page 7-15
Intelligent Power Supply Design Tips ‘n Tricks
Method 2 – Linear Control
When using PWM, the voltage will vary between
a maximum and a minimum, however, is it also
possible to use a linear method to control fan
speed, as shown in Figure 14-4.
Figure 14-4: Linear Control Drive
12V
VREF
+
-
Out
R1
TIP #15High Current Delta-Sigma
Based Current Measurement
Using a Slotted Ferrite and
Hall Effect Device
Many current sensors rely on ferrite cores.
Non-linearity in the ferrite can lead to inaccurate
results, especially at high currents. One way to
avoid the non-linearities is to keep the net flux
in the ferrite near zero. Consider the circuit in
Figure 15-1.
Figure 15-1: Hall Effect Current
Measurement Schematic
PIC® MCU
+
The voltage applied at the non-inverting terminal
of the op amp is used to vary the voltage
across the op amp. The non-inverting terminal
voltage can be produced by a Digital-to-Analog
Converter (DAC) or by the method shown in
Tip #11.
When using this method, care must be taken
to ensure that the fan voltage is not too low or
the fan will stop spinning. One advantage this
method has over PWM is that the tachometer
output will function properly on 3-wire fans.
The disadvantage, however, is that it often
offers less speed control. For example, a 12V
fan will not spin below 8V, so a range of only
4V is available for speed control. A 5V fan will
not spin below 4V and so the control range is
only 1V, which is often unacceptable. Another
disadvantage is the power consumption of the
circuit. The transistor will dissipate more power
than the PWM method.
Page 7-16-DS01146B
MOSFET Driver
-
R2
VDD
VREF
Hall Effect
Sensor
The Hall effect sensor output is proportional to
the current being measured. When Iin = 0 amps,
the output of the sensor will be Vdd/2. A current
passing through the sensor in one direction will
increase the output of the sensor, and a current
in the other direction will decrease the output of
the sensor.
The output of the comparator is used to drive a
coil of wire wound around the ferrite core. This
coil of wire will be used to create flux in the
opposite direction as the flux imposed in the
core.
© 2009 Microchip Inc.
Intelligent Power Supply Design Tips ‘n Tricks
TIP #16Implementing a PID
Feedback Control in a
PIC12F683-Based SMPS
Design
Figure 15-2: Flux Directions
Flux due to input current
Simple switching power supplies can be
controlled digitally using a Proportional Integral
Derivative (PID) algorithm in place of an analog
error amplifier and sensing the voltage using the
Analog-to-Digital Converter (ADC).
IIN
Flux due to
driven coil
Figure 16-1: Simple PID Power Supply
+5V
The net flux in the core should be approximately
zero. Because the flux will always be very near
zero, the core will be very linear over the small
operating range.
When Iin = 0, the output of the comparator
will have an approximate 50% duty cycle.
As the current moves one direction, the duty
cycle will increase. As the current moves the
other direction, the duty cycle will decrease.
By measuring the duty cycle of the resulting
comparator output, we can determine the value
of Iin.
Finally, a Delta-Sigma ADC can be used to
perform the actual measurement. Features such
as comparator sync and Timer1 gate allow the
Delta-Sigma conversion to be taken care of
entirely in hardware. By taking 65,536 (2^16)
samples and counting the number of samples
that the comparator output is low or high, we
can obtain a 16-bit A/D result.
Example schematic and software are provided
for the PIC12F683 in both C and Assembly.
For more information on using a PIC MCU to
implement a Delta-Sigma converter, please
refer to AN700, “Make a Delta-Sigma Converter
Using a Microcontroller’s Analog Comparator
Module” (DS00700), which includes example
software.
© 2009 Microchip Inc.
VSENSE
PIC12F683
VDD
AN0
GP5
GP1
GP4
CCP1 VSS
GP3
+5V
R1
C2
Q1
L1
VOUT
VSENSE
+
D2
C1
R2
R3
The design in Figure 16-1 utilizes an 8-pin
PIC12F683 PIC MCU in a buck topology.
The PIC12F683 has the basic building blocks
needed to implement this type of power supply:
an A/D converter and a CCP module.
Figure 16-2: PID Block Diagram
PIC® Microcontroller
A/D Voltage
Sense
+Desired
Value
Software
PID
Routine
CCP
Duty Cycle
DS01146B-Page 7-17
Intelligent Power Supply Design Tips ‘n Tricks
The A/D converter is used to sense the output
voltage for this particular application, Vdd is
used as the reference to the A/D converter. If
desired, a more accurate reference could be
used. The output voltage is subtracted from the
desired value, creating an error value.
This error becomes the input to the PID routine.
The PID routine uses the error voltage to
determine the appropriate duty cycle for the
output drive. The PID constants are weighted
so that the main portion of the control is
proportional and integral. The differential
component is not essential to this system and is
not used. Furthermore, the PID constants could
be optimized if a particular type of transient
response was desired, or if a predictable
transient load was to be connected.
Finally, the CCP module is used to create a
PWM signal at the chosen frequency with the
proper duty cycle.
Example software is provided for the
PIC12F683 using the schematic in Figure 16-1.
The following application notes are related to
PID control algorithms and all include example
software:
•AN258, “Low Cost USB Microcontroller
Programmer The Building of the PICkit® 1
Flash Starter Kit” (DS00258)
•AN937, “Implementing a PID Controller Using
a PIC18 MCU” (DS00937)
•AN964, “Software PID Control of an Inverted
Pendulum Using the PIC16F684” (DS00937)
Page 7-18-DS01146B
TIP #17An Error Detection and
Restart Controller
An error detection and restart controller can
be created by combining Tip #18 and Tip #19.
The controller uses the PIC microcontroller
(MCU) Analog-to-Digital Converter (ADC) for
making voltage and current measurements.
Input voltage, input current, output voltage,
output current, temperature and more can all
be measured using the A/D converter. The
on-board comparators are used for monitoring
faster signals, such as output current,
ensuring that they do not exceed maximum
allowable levels. Many PIC MCUs have
internal programmable comparator references,
simplifying the circuit.
Figure 17-1: Block Diagram
Output Voltage
Input Voltage
Input Current
Status
Indicators
PIC® MCU
Output Voltage
Temperature
Using a PIC MCU as a controller allows
for a greater level of intelligence in system
monitoring. Rather than a single event causing
a shutdown, a combination of events can
cause a shutdown. A certain number of events
in a certain time frame or possibly a certain
sequence of events could be responsible for a
shutdown.
The PIC MCU has the ability to restart the
supply based on the shutdown event. Some
events (such as overcurrent) may call for
immediate restart, while other events (such as
overtemperature) may require a delay before
restarting, perhaps monitoring other parameters
and using those to determine when to restart.
It is also possible to build this type of error
detection and restart controller into many of the
tips listed within this guide.
© 2009 Microchip Inc.
Intelligent Power Supply Design Tips ‘n Tricks
TIP #18Data-Indexed Software State
Machine
A state machine can be used to simplify a task
by breaking the task up into smaller segments.
Based on a state variable, the task performed
or the data used by the state machine can be
changed. There are three basic types of state
machines: data-indexed, execution indexed
and a hybrid of the two. This tip will focus on a
data-indexed state machine.
The data-indexed state machine is ideal for
monitoring multiple analog inputs with the
Analog-to-Digital Converter (ADC). The state
variable in these state machines determines
which data is acted upon. In this case, the
tasks of changing the ADC channel, storing the
current result and starting a new conversion are
always the same.
A very simple flow diagram for a data-indexed
state machine is shown in Figure 18-1.
As shown in Figure 18-1, a constant array
(CONSTANT[i]) can be created to store the
values to be loaded into the ADC control
register to change the ADC channel.
Furthermore, a data array (ADCDATA[i]) can be
used to store the results of the ADC conversion.
Finally, the next conversion is started and the
logic required to increment and bind the state
variable is executed.
This particular example used the ADC interrupt
to signal when a conversion has completed, and
will attempt to take measurements as quickly
as possible. A subroutine could also be built to
perform the same task, allowing the user to call
the subroutine when needed.
Example software is provided using the
PIC16F676 and RS-232 to monitor several ADC
channels.
Figure 18-1: Data-Indexed State Machine
Flowchart
ADC Interrupt
Load ADC control register
with CONSTANT[i] to
change ADC channel
Store current measurement
data to ADCDATA[1]
registers
Start next ADC conversion
Increment state variable,
checking for rollover
End ADC Interrupt
Service Routine
© 2009 Microchip Inc.
DS01146B-Page 7-19
Intelligent Power Supply Design Tips ‘n Tricks
TIP #19Execution-Indexed Software
State Machine
Another common type of state machine is the
execution-indexed state machine. This type of
state machine uses a state variable in order to
determine what is executed. In C, this can be
thought of as the switch statement structure as
shown in Example 19-1.
Example 19-1: Example Using Switch
Statement
SWITCH (State)
{
CASE 0: IF (in_key()==5) THEN state = 1;
Break;
CASE 1: IF (in_key()==8) THEN State = 2;
Else State = 0;
Break;
CASE 2: IF (in_key()==3) THEN State = 3;
Else State = 0;
Break;
CASE 3: IF (in_key()==2) THEN UNLOCK();
Else State = 0;
Break;
}
Each time the software runs through the loop,
the action taken by the state machine changes
with the value in the state variable. By allowing
the state machine to control its own state
variable, it adds memory, or history, because
the current state will be based on previous
states. The microcontroller is able to make
current decisions based on previous inputs and
data.
In assembly, an execution-indexed state
machine can be implemented using a jump
table.
Page 7-20-DS01146B
Example 19-2: Example Using a Jump Table
MOVFW
ADDWF
state
PCL,f
GOTO
GOTO
GOTO
GOTO
GOTO
GOTO
state0
state1
state2
state3
state4
state5
;load state into w
;jump to state
;number
;state 0
;state 1
;state 2
;state 3
;state 4
;state 5
In Example 19-2, the program will jump to a
GOTO statement based on the state variable.
The GOTO statement will send the program to
the proper branch. Caution must be taken to
ensure that the variable will never be larger than
intended. For example, six states (000 to 101)
require a three-bit state variable. Should the
state variable be set to an undefined state (110
to 111), program behavior would become
unpredictable.
Means for safeguarding this problem include:
•Mask off any unused bits of the variable. In
the above example, ANDLW b’00000111’ will
ensure that only the lower 3 bits of the number
contain a value.
•Add extra cases to ensure that there will
always be a known jump. For example in this
case, two extra states must be added and
used as error or Reset states.
© 2009 Microchip Inc.
Intelligent Power Supply Design Tips ‘n Tricks
Many sensors and references tend to drift
with temperature. For example, the MCP9700
specification states that its typical is ±0.5°C and
its max error is ±4°C.
Figure 20-1: MCP9700 Accuracy
Accuracy (°C)
6.0
Spec. Limit
2.0
0.0
-4.0
-55
0.3
0.2
0.1
0.0
-0.1
-0.2
4.0
-2.0
Figure 20-2: MCP9700 Average Accuracy
After Compensation
Accuracy (°C)
TIP #20Compensating Sensors
Digitally
+σ
Average
-σ
-35 -15
5
25 45 65
Temperature (°C)
85
105 125
Figure 20-1 shows the accuracy of a 100
sample lot of MCP9700 temperature sensors.
Despite the fact that the sensor’s error is
nonlinear, a PIC microcontroller (MCU) can be
used to compensate the sensor’s reading.
Polynomials can be fitted to the average error of
the sensor. Each time a temperature reading is
received, the PIC MCU can use the measured
result and the error compensation polynomials
to determine what the true temperature is.
© 2009 Microchip Inc.
-0.3
-55
Average
-35
-15
5
25 45 65
Temperature (°C)
85
105 125
Figure 20-2 shows the average accuracy for the
100 sample lot of MCP9700 temperature
sensors after compensation. The average error
has been decreased over the full temperature
range.
It is also possible to compensate for error from
voltage references using this method.
For more information on compensating
a temperature sensor digitally, refer to
AN1001, “IC Temperature Sensor Accuracy
Compensation with a PIC Microcontroller”
(DS01001).
DS01146B-Page 7-21
Intelligent Power Supply Design Tips ‘n Tricks
TIP #21Using Output Voltage
Monitoring to Create a
Self-Calibration Function
A PIC microcontroller can be used to create
a switching power supply controlled by a PID
loop (as described in Tip #16). This type of
power supply senses its output voltage digitally,
compares that voltage to the desired reference
voltage and makes duty cycle changes
accordingly. Without calibration, it is sensitive to
component tolerances.
Figure 21-1: Typical Power Supply Output
Stage
VOUT
Switching Circuitry
C1
R1
Voltage Sense
R2
Page 7-22-DS01146B
The output stage of many power supplies is
similar to Figure 21-1. R1 and R2 are used to
set the ratio of the voltage that is sensed and
compared to the reference.
A simple means of calibrating this type of power
supply is as follows:
1. Supply a known reference voltage to the
output of the supply.
2.Place the supply in Calibration mode and
allow it to sense that reference voltage.
By providing the supply with the output voltage
that it is to produce, it can then sense the
voltage across the resistor divider and store
the sensed value. Regardless of resistor
tolerances, the sensed value will always
correspond to the proper output value for that
particular supply.
Futhermore, this setup could be combined with
Tip #20 to calibrate at several temperatures.
This setup could also be used to create a
programmable power supply by changing the
supplied reference and the resistor divider for
voltage feedback.
© 2009 Microchip Inc.
CHAPTER 8
3V Tips ‘n Tricks
3V Tips ‘n Tricks
Table Of Contents
TIPS ‘N TRICKS INTRODUCTION
TIP #1: Powering 3.3V Systems From 5V
Using an LDO Regulator.....................
TIP #2: Low-Cost Alternative Power System
Using a Zener Diode...........................
TIP #3: Lower Cost Alternative Power System
Using 3 Rectifier Diodes......................
TIP #4: Powering 3.3V Systems From 5V
Using Switching Regulators................
TIP #5: 3.3V → 5V Direct Connect..................
TIP #6: 3.3V → 5V Using a MOSFET
Translator............................................
TIP #7: 3.3V → 5V Using A Diode Offset.........
© 2009 Microchip Technology Inc.
8-3
8-4
8-4
8-5
8-6
8-6
8-7
TIP #8:
TIP #9:
TIP #10:
TIP #11:
TIP #12:
TIP #13:
TIP #14:
TIP #15:
TIP #16:
TIP #17:
TIP #18:
TIP #19:
3.3V → 5V Using A Voltage
Comparator......................................... 8-8
5V → 3.3V Direct Connect.................. 8-9
5V → 3.3V With Diode Clamp............. 8-9
5V → 3.3V Active Clamp..................... 8-10
5V → 3.3V Resistor Divider................. 8-10
3.3V → 5V Level Translators............... 8-12
3.3V → 5V Analog Gain Block............. 8-13
3.3V → 5V Analog Offset Block........... 8-13
5V → 3.3V Active Analog Attenuator... 8-14
5V → 3V Analog Limiter...................... 8-15
Driving Bipolar Transistors.................. 8-16
Driving N-Channel MOSFET
Transistors........................................... 8-18
DS01146B-Page 8-1
3V Tips ‘n Tricks
TIPS ‘N TRICKS INTRODUCTION
Overview - the 3.3 Volt to 5 Volt Connection
One of the by-products of our ever increasing
need for processing speed is the steady
reduction in the size of the transistors used
to build microcontrollers. Up-integration at
cheaper cost also drives the need for smaller
geometries. With reduced size comes a
reduction in the transistor breakdown voltage,
and ultimately, a reduction in the supply voltage
when the breakdown voltage falls below
the supply voltage. So, as speeds increase
and complexity mounts, it is an inevitable
consequence that the supply voltages would
drop from 5V to 3.3V, or even 1.8V for high
density devices.
Microchip microcontrollers have reached a
sufficient level of speed and complexity that
they too are making the transition to sub-5V
supply voltages. The challenge is that most of
the interface circuitry is still designed for 5V
supplies. This means that, as designers, we
now face the task of interfacing 3.3V and 5V
systems. Further, the task includes not only
logic level translation, but also powering the
3.3V systems and translating analog signals
across the 3.3V/5V barrier.
Power Supplies
One of the first 3.3V challenges is generating
the 3.3V supply voltage. Given that we are
discussing interfacing 5V systems to 3.3V
systems, we can assume that we have a stable
5 Vdc supply. This section will present voltage
regulator solutions designed for the 5V to 3.3V
transition. A design with only modest current
requirements may use a simple linear regulator.
Higher current needs may dictate a switching
regulator solution. Cost sensitive applications
may need the simplicity of a discrete diode
regulator. Examples from each of these areas
are included here, with the necessary support
information to adapt to a wide variety of end
applications.
Table 1: Power Supply Comparisons
Vreg
Iq
Eff.
Size
Cost
Transient
Response
Zener
Shun
Reg.
10%
Typ
5 mA
60%
Sm
Low
Poor
Series
Linear
Reg.
0.4%
Typ
1 µA
to
100 µA
60%
Sm
Med
Excellent
Switching
Buck
Reg.
0.4%
Typ
30 µA
to
2 mA
93%
Med
to
Lrg
High
Good
Method
This Tips ‘n Tricks book addresses these
challenges with a collection of power supply
building blocks, digital level translation blocks
and even analog translation blocks. Throughout
the book, multiple options are presented for
each of the transitions, spanning the range from
all-in-one interface devices, to low-cost discrete
solutions. In short, all the blocks a designer is
likely to need for handling the 3.3V challenge,
whether the driving force is complexity, cost or
size.
Additional information can be found on the
Microchip web site at www.microchip.com/3volts.
Note:The tips ‘n tricks presented here
assume a 3.3V supply. However,
the techniques work equally well for
other supply voltages with the
appropriate modifications.
Page 8-2-DS01146B
© 2009 Microchip Technology Inc.
3V Tips ‘n Tricks
TIP #1Powering 3.3V Systems From
5V Using an LDO Regulator
The dropout voltage of standard three-terminal
linear regulators is typically 2.0-3.0V. This
precludes them from being used to convert 5V
to 3.3V reliably. Low Dropout (LDO) regulators,
with a dropout voltage in the few hundred
milli-volt range, are perfectly suited for this
type of application. Figure 1-1 contains a block
diagram of a basic LDO system with appropriate
current elements labeled. From this figure it
can be seen that an LDO consists of four main
elements:
1.Pass transistor
2.Bandgap reference
3.Operational amplifier
4.Feedback resistor divider
When selecting an LDO, it is important to know
what distinguishes one LDO from another.
Device quiescent current, package size
and type are important device parameters.
Evaluating for each parameter for the specific
application yields an optimal design.
© 2009 Microchip Technology Inc.
Figure 1-1: LDO Voltage Regulator
IIN
IOUT
VREF
VIN
C1
C2
+
RL
IGND
An LDOs quiescent current, Iq, is the device
ground current, Ignd, while the device is
operating at no load. Ignd is the current used by
the LDO to perform the regulating operation.
The efficiency of an LDO can be approximated
as the output voltage divided by the input
voltage when Iout>>Iq. However, at light loads,
the Iq must be taken into account when
calculating the efficiency. An LDO with lower Iq
will have a higher light load efficiency. This
increase in light load efficiency has a negative
effect on the LDO performance. Higher
quiescent current LDOs are able to respond
quicker to sudden line and load transitions.
DS01146B-Page 8-3
3V Tips ‘n Tricks
TIP #2Low-Cost Alternative Power
System Using a Zener Diode
Details a low-cost regulator alternative using a
Zener diode.
Figure 2-1: Zener Supply
+5V
PIC® MCU
R1
VDD
470Ω
D1
C1
0.1 µF
VSS
A simple, low-cost 3.3V regulator can be made
out of a Zener diode and a resistor as shown in
Figure 2-1. In many applications, this circuit can
be a cost-effective alternative to using a LDO
regulator. However, this regulator is more load
sensitive than a LDO regulator. Additionally, it is
less energy efficient, as power is always being
dissipated in R1 and D1.
R1 limits the current to D1 and the PIC MCU
so that Vdd stays within the allowable range.
Because the reverse voltage across a Zener
diode varies as the current through it changes,
the value of R1 needs to be considered
carefully.
R1 must be sized so that at maximum load,
typically when the PIC MCU is running and is
driving its outputs high, the voltage drop across
R1 is low enough so that the PIC MCU has
enough voltage to operate. Also, R1 must be
sized so that at minimum load, typically when
the PIC MCU is in Reset, that Vdd does not
exceed either the Zener diode’s power rating or
the maximum Vdd for the PIC MCU.
Page 8-4-DS01146B
TIP #3Lower Cost Alternative
Power System Using 3
Rectifier Diodes
Figure 3-1 details a lower cost regulator
alternative using 3 rectifier diodes.
Figure 3-1: Diode Supply
D2
+5V
D1
PIC® MCU
D3
VDD
R1
C1
0.1 µF
VSS
We can also use the forward drop of a series of
normal switching diodes to drop the voltage
going into the PIC MCU. This can be even more
cost-effective than the Zener diode regulator.
The current draw from this design is typically
less than a circuit using a Zener.
The number of diodes needed varies based on
the forward voltage of the diode selected. The
voltage drop across diodes D1-D3 is a function
of the current through the diodes. R1 is present
to keep the voltage at the PIC MCUs Vdd pin
from exceeding the PIC MCUs maximum Vdd
at minimum loads (typically when the PIC MCU
is in Reset or sleeping). Depending on the
other circuitry connected to Vdd, this resistor
may have its value increased or possibly even
eliminated entirely. Diodes D1-D3 must be
selected so that at maximum load, typically
when the PIC is running and is driving its
outputs high, the voltage drop across D1-D3 is
low enough to meet the PIC MCUs minimum
Vdd requirements.
© 2009 Microchip Technology Inc.
3V Tips ‘n Tricks
TIP #4Powering 3.3V Systems From
5V Using Switching Regulators
A buck switching regulator, shown in Figure
4-1, is an inductor-based converter used to
step-down an input voltage source to a lower
magnitude output voltage. The regulation of
the output is achieved by controlling the ON
time of MOSFET Q1. Since the MOSFET is
either in a lower or high resistive state (ON or
OFF, respectively), a high source voltage can
be converted to a lower output voltage very
efficiently.
The relationship between the input and output
voltage can be established by balancing the
volt-time of the inductor during both states of
Q1.
Equation 4-4
Zo ≡ √ L/C
C = L/R2 = (Io2 * L)/Vo2
When choosing a diode for D1, choose a device
with a sufficient current rating to handle the
inductor current during the discharge part of the
pulse cycle (Il).
Figure 4-1: Buck Regulator
L
Q1
VS
D1
C
VO
RL
Equation 4-1
(Vs - Vo) * ton = Vo * (T - ton)
Where: T ≡ ton/Duty_Cycle
It therefore follows that for MOSFET Q1:
Equation 4-2
Duty_Cycleq1 = Vo/Vs
When choosing an inductor value, a good
starting point is to select a value to produce a
maximum peak-to-peak ripple current in the
inductor equal to ten percent of the maximum
load current.
Digital Interfacing
When interfacing two devices that operate at
different voltages, it is imperative to know the
output and input thresholds of both devices.
Once these values are known, a technique can
be selected for interfacing the devices based on
the other requirements of your application. Table
4-1 contains the output and input thresholds that
will be used throughout this document. When
designing an interface, make sure to reference
your manufacturers data sheet for the actual
threshold levels.
Table 4-1: Input/Output Thresholds
Equation 4-3
V = L * (di/dt)
L = (Vs - Vo) * (ton/Io * 0.10)
When choosing an output capacitor value,
a good starting point is to set the LC filter
characteristic impedance equal to the load
resistance. This produces an acceptable voltage
overshoot when operating at full load and
having the load abruptly removed.
© 2009 Microchip Technology Inc.
Voh min
Vol max
Vih min
Vil max
5V TTL
2.4V
0.5V
2.0V
0.8V
3.3V
LVTTL
2.4V
0.4V
2.0V
0.8V
5V
CMOS
4.7V
(Vcc-0.3V)
0.5V
3.5V
(0.7xVcc)
1.5V
(0.3xVcc)
3.3V
LVCMOS
3.0V
(Vcc-0.3V)
0.5V
2.3V
(0.7xVcc)
1.0V
(0.3xVcc)
DS01146B-Page 8-5
3V Tips ‘n Tricks
TIP #53.3V → 5V Direct Connect
The simplest and most desired way to connect
a 3.3V output to a 5V input is by a direct
connection. This can be done only if the
following 2 requirements are met:
•The Voh of the 3.3V output is greater than the
Vih of the 5V input
•The Vol of the 3.3V output is less than the Vil
of the 5V input
An example of when this technique can be
used is interfacing a 3.3V LVCMOS output to
a 5V TTL input. From the values given in Table
4-1, it can clearly be seen that both of these
requirements are met.
3.3V LVCMOS Voh of 3.0 volts is greater than
5V TTL Vih of 2.0 volts, and
3.3V LVCMOS Vol of 0.5 volts is less than 5V
TTL Vil of 0.8 volts.
When both of these requirements are not met,
some additional circuitry will be needed to
interface the two parts. See Tips 6, 7, 8 and 13
for possible solutions.
TIP #63.3V → 5V Using a MOSFET
Translator
In order to drive any 5V input that has a higher
Vih than the Voh of a 3.3V CMOS part, some
additional circuitry is needed. A low-cost two
component solution is shown in Figure 6-1.
When selecting the value for R1, there are two
parameters that need to be considered; the
switching speed of the input and the current
consumption through R1. When switching the
input from a ‘0’ to a ‘1’, you will have to account
for the time the input takes to rise because of
the RC time constant formed by R1, and the
input capacitance of the 5V input plus any
stray capacitance on the board. The speed at
which you can switch the input is given by the
following equation:
Equation 6-1
Tsw = 3 x R1 x (Cin + Cs)
Since the input and stray capacitance of the
board are fixed, the only way to speed up the
switching of the input is to lower the resistance
of R1. The trade-off of lowering the resistance of
R1 to get faster switching times is the increase
in current draw when the 5V input remains low.
The switching to a ‘0’ will typically be much
faster than switching to a ‘1’ because the ON
resistance of the N-channel MOSFET will be
much smaller than R1. Also, when selecting the
N-channel FET, select a FET that has a lower
Vgs threshold voltage than the Voh of 3.3V
output.
Figure 6-1: MOSFET Translator
5V
R1
3.3V
LVCMOS
Output
Page 8-6-DS01146B
5V Input
© 2009 Microchip Technology Inc.
3V Tips ‘n Tricks
TIP #7 3.3V → 5V Using a Diode Offset
The inputs voltage thresholds for 5V CMOS and
the output drive voltage for 3.3V LVTTL and
LVCMOS are listed in Table 7-1.
Table 7-1: Input/Output Thresholds
5V CMOS
Input
3.3V LVTTL
Output
3.3V LVCMOS
Output
High
Threshold
> 3.5V
> 2.4V
> 3.0V
Low
Threshold
< 1.5V
< 0.4V
< 0.5V
Note that both the high and low threshold input
voltages for the 5V CMOS inputs are about a
volt higher than the 3.3V outputs. So, even if
the output from the 3.3V system could be offset,
there would be little or no margin for noise or
component tolerance. What is needed is a
circuit that offsets the outputs and increases
the difference between the high and low output
voltages.
Figure 7-1: Diode Offset
3.3V
D1
R1
If we create a diode offset circuit (see Figure
7-1), the output low voltage is increased by
the forward voltage of the diode D1, typically
0.7V, creating a low voltage at the 5V CMOS
input of 1.1V to 1.2V. This is well within the
low threshold input voltage for the 5V CMOS
input. The output high voltage is set by the
pull-up resistor and diode D2, tied to the 3.3V
supply. This puts the output high voltage at
approximately 0.7V above the 3.3V supply,
or 4.0 to 4.1V, which is well above the 3.5V
threshold for the 5V CMOS input.
Note:For the circuit to work properly, the
pull-up resistor must be significantly
smaller than the input resistance of
the 5V CMOS input, to prevent a
reduction in the output voltage due
to a resistor divider effect at the
input. The pull-up resistor must also
be large enough to keep the output
current loading on the 3.3V output
within the specification of the device.
5V
D2
3.3V Output
5V Input
When output voltage specifications are
determined, it is done assuming that the output
is driving a load between the output and ground
for the high output, and a load between 3.3V
and the output for the low output. If the load for
the high threshold is actually between the output
and 3.3V, then the output voltage is actually
much higher as the load resistor is the
mechanism that is pulling the output up, instead
of the output transistor.
© 2009 Microchip Technology Inc.
DS01146B-Page 8-7
3V Tips ‘n Tricks
TIP #83.3V → 5V Using a Voltage
Comparator
The basic operation of the comparator is as
follows:
•When the voltage at the inverting (-) input is
greater than that at the non-inverting (+) input,
the output of the comparator swings to Vss.
•When the voltage at the non-inverting (+) input
is greater than that at the non-inverting (-)
input, the output of the comparator is in a high
state.
To preserve the polarity of the 3.3V output,
the 3.3V output must be connected to the
non-inverting input of the comparator. The
inverting input of the comparator is connected to
a reference voltage determined by R1 and R2,
as shown in Figure 8-1.
Figure 8-1: Comparator Translator
Given that R1 and R2 are related by the logic
levels:
Equation 8-2:
R1 = R2
(
5V
1.75V
-1
)
assuming a value of 1K for R2, R1 is 1.8K.
An op amp wired up as a comparator can be
used to convert a 3.3V input signal to a 5V
output signal. This is done using the property
of the comparator that forces the output to
swing high (Vdd) or low (Vss), depending on the
magnitude of difference in voltage between its
‘inverting’ input and ‘non-inverting’ input.
Note:For the op amp to work properly
when powered by 5V, the output
must be capable of rail-to-rail drive.
Figure 8-2: Op Amp as a Comparator
5V (VDD)
R1
RO
5V (VDD)
+
VSS
3.3V Output
-
R2
R1
5V Input
+
3.3V Output
R2
VSS
Calculating R1 and R2
5V Input
VSS
VSS
The ratio of R1 and R2 depends on the logic
levels of the input signal. The inverting input
should be set to a voltage halfway between Vol
and Voh for the 3.3V output. For an LVCMOS
output, this voltage is:
Equation 8-1:
1.75V = (3.0V +.5V)
2
Page 8-8-DS01146B
© 2009 Microchip Technology Inc.
3V Tips ‘n Tricks
TIP #95V → 3.3V Direct Connect
TIP #105V → 3.3V With Diode Clamp
5V outputs have a typical Voh of 4.7 volts and
a Vol of 0.4 volts and a 3.3V LVCMOS input
will have a typical Vih of 0.7 x Vdd and a Vil of
0.2 x Vdd.
Many manufacturers protect their I/O pins from
exceeding the maximum allowable voltage
specification by using clamping diodes. These
clamping diodes keep the pin from going more
than a diode drop below Vss and a diode drop
above Vdd. To use the clamping diode to protect
the input, you still need to look at the current
through the clamping diode. The current through
the clamp diodes should be kept small (in the
micro amp range). If the current through the
clamping diodes gets too large, then you risk
the part latching up. Since the source resistance
of a 5V output is typically around 10Ω, an
additional series resistor is still needed to limit
the current through the clamping diode as
shown Figure 10-1. The consequence of using
the series resistor is it will reduce the speed at
which we can switch the input because the RC
time constant formed the capacitance of the pin
(Cl).
When the 5V output is driving low, there are no
problems because the 0.4 volt output is less
than in the input threshold of 0.8 volts. When
the 5V output is high, the Voh of 4.7 volts is
greater than 2.1 volt Vih, therefore, we can
directly connect the 2 pins with no conflicts if the
3.3V CMOS input is 5 volt tolerant.
Figure 9-1: 5V Tolerant Input
RS
5V TTL
Output
3V CMOS
with
5V Tolerant
Input
Figure 10-1: Clamping Diodes on the Input
If the 3.3V CMOS input is not 5 volt tolerant,
then there will be an issue because the
maximum volt specification of the input will be
exceeded.
VDD
RS
RSER
3.3V
Input
See Tips 10-13 for possible solutions.
5V
Output
CL
If the clamping diodes are not present, a single
external diode can be added to the circuit as
shown in Figure 10-2.
Figure 10-2: Without Clamping Diodes
VDD
RS
5V
Output
© 2009 Microchip Technology Inc.
D1
RSER
CL
3.3V
Input
DS01146B-Page 8-9
3V Tips ‘n Tricks
TIP #11 5V → 3.3V Active Clamp
TIP #125V → 3.3V Resistor Divider
One problem with using a diode clamp is that
it injects current onto the 3.3V power supply.
In designs with a high current 5V outputs,
and lightly loaded 3.3V power supply rails,
this injected current can float the 3.3V supply
voltage above 3.3V. To prevent this problem, a
transistor can be substituted which routes the
excess output drive current to ground instead of
the 3.3V supply. Figure 11-1 shows the resulting
circuit.
A simple resistor divider can be used to reduce
the output of a 5V device to levels appropriate
for a 3.3V device input. An equivalent circuit of
this interface is shown in Figure 12-1.
Figure 11-1: Transistor Clamp
Figure 12-1: Resistive Interface Equivalent
Circuit
5V Device
RS VS
3.3V Device
R1
VL
CL
R2
RL
CS
R1
5V Output
3.3V Input
Q1
3.3V
The base-emitter junction of Q1 performs the
same function as the diode in a diode clamp
circuit. The difference is that only a small
percentage of the emitter current flows out of
the base of the transistor to the 3.3V rail, the
bulk of the current is routed to the collector
where it passes harmlessly to ground. The ratio
of base current to collector current is dictated by
the current gain of the transistor, typically
10-400, depending upon which transistor is
used.
Page 8-10-DS01146B
Typically, the source resistance, Rs, is very
small (less than 10Ω) so its affect on R1 will be
negligible provided that R1 is chosen to be
much larger than Rs. At the receive end, the
load resistance, Rl, is very large (greater than
500 kΩ) so its affect on R2 will be negligible
provided that R2 is chosen to be much less than
R l.
There is a trade-off between power dissipation
and transition times. To keep the power
requirements of the interface circuit at a
minimum, the series resistance of R1 and R2
should be as large as possible. However, the
load capacitance, which is the combination of
the stray capacitance, Cs, and the 3.3V device
input capacitance, Cl, can adversely affect the
rise and fall times of the input signal. Rise and
fall times can be unacceptably long if R1 and
R2 are too large.
© 2009 Microchip Technology Inc.
3V Tips ‘n Tricks
Neglecting the affects of Rs and Rl, the formula
for determining the values for R1 and R2 is
given by Equation 12-1.
Equation 12-1: Divider Values
Vs
=
R1 + R2
Vl
R2
The calculation to determine the maximum
resistances is shown in Equation 12-3.
Equation 12-3: Example Calculation
Solve Equation 12-2 for R:
; General relationship
; Solving for R1
R1 = ( Vs - Vl ) • R2
Vl
; Substituting voltages
R1 = 0.515 • R2
The formula for determining the rise and fall
times is given in Equation 12-2. For circuit
analysis, the Thevenin equivalent is used to
determine the applied voltage, Va, and the
series resistance, R. The Thevenin equivalent
is defined as the open circuit voltage divided
by the short circuit current. The Thevenin
equivalent, R, is determined to be 0.66*R1
and the Thevenin equivalent, Va, is determined
to be 0.66*Vs for the circuit shown in Figure
12-2 according to the limitations imposed by
Equation 12-2.
R = -
C • ln
(
t
Vf - Va
Vi - Va
)
Substitute values:
-7
R = -
10 • 10
3 - (0.66 • 5)
-12
35 • 10 • ln 0.3 - (0.66 • 5)
(
)
Thevenin equivalent maximum R:
R = 12408
Solve for maximum R1 and R2:
R1 = 0.66 • R
R2 = R1
0.515
R1 = 8190
R2 = 15902
Equation 12-2: Rise/Fall Time
t = Where:
t =
R =
C =
Vi =
Vf =
Va =
[ R • C • ln ( VV - -VV ) ]
f
i
a
a
Rise or Fall time
0.66*R1
Cs+Cl
Initial voltage on C (Vl)
Final voltage on C (Vl)
Applied voltage (0.66*Vs)
As an example, suppose the following
conditions exist:
•Stray capacitance = 30 pF
•Load capacitance = 5 pF
•Maximum rise time from 0.3V to 3V ≤ 1 µS
•Applied source voltage Vs = 5V
© 2009 Microchip Technology Inc.
DS01146B-Page 8-11
3V Tips ‘n Tricks
TIP #133.3V → 5V Level Translators
While level translation can be done discretely, it
is often preferred to use an integrated solution.
Level translators are available in a wide range
of capabilities. There are unidirectional and
bidirectional configurations, different voltage
translations and different speeds, all giving the
user the ability to select the best solution.
Board-level communication between devices
(e.g., MCU to peripheral) is most often done
by either SPI or I2C™. For SPI, it may be
appropriate to use a unidirectional level
translator and for I2C, it is necessary to use a
bidirectional solution. Figure 13-1 illustrates
both solutions.
Figure 13-1: Level Translator
VDD
5.0V
VL
3.3V
P
P C MC
C
PC
The final 3.3V to 5V interface challenge is the
translation of analog signals across the power
supply barrier. While low level signals will
probably not require external circuitry, signals
moving between 3.3V and 5V systems will be
affected by the change in supply. For example,
a 1V peak analog signal converted by an ADC
in a 3.3V system will have greater resolution
than an ADC in a 5V system, simply because
more of the ADCs range is used to convert the
signal in the 3.3V ADC. Alternately, the relatively
higher signal amplitude in a 3.3V system may
have problems with the system’s lower common
mode voltage limitations.
Therefore, some interface circuitry, to
compensate for the differences, may be
needed. This section will discuss interface
circuitry to help alleviate these problems when
the signal makes the transition between the
different supply voltages.
MCP2515
Unidirectional
Level Translator
MCP2551
CAN
Transceiver
nCS
SCK
SPI
Analog
SDI
SPI
CAN
SDO
VDD
5.0V
VL
3.3V
P
P C MC
C
PC
I2C™
VL
VL
Bidirectional
Level Translator
MCP 221
VDD
SCL
VDD
I2C™
12-bit
ADC
SDA
Page 8-12-DS01146B
© 2009 Microchip Technology Inc.
3V Tips ‘n Tricks
TIP #143.3V → 5V Analog Gain Block
To scale analog voltage up when going from
3.3V supply to 5V supply. The 33 kΩ and 17 kΩ
set the op amp gain so that the full scale range
is used in both sides. The 11 kΩ resistor limits
current back to the 3.3V circuitry.
Figure 14-1: Analog Gain Block
+3.3V
+5.0V
+5.0V
+
11k
MCP6XXX
-
33k 17k
TIP #153.3V → 5V Analog
Offset Block
Offsetting an analog voltage for translation
between 3.3V and 5V.
Shift an analog voltage from 3.3V supply to 5V
supply. The 147 kΩ and 30.1 kΩ resistors on
the top right and the +5V supply voltage are
equivalent to a 0.85V voltage source in series
with a 25 kΩ resistor. This equivalent 25 kΩ
resistance, the three 25 kΩ resistors, and the
op amp form a difference amplifier with a gain
of 1 V/V. The 0.85V equivalent voltage source
shifts any signal seen at the input up by the
same amount; signals centered at 3.3V/2 =
1.65V will also be centered at 5.0V/2 = 2.50V.
The top left resistor limits current from the 5V
circuitry.
Figure 15-1: Analog Offset Block
+3.3V
+5.0V
147k
25k
+5.0V
30.1k
+5.0V
MCP6XXX
+
-
25k
© 2009 Microchip Technology Inc.
25k
DS01146B-Page 8-13
3V Tips ‘n Tricks
TIP #165V → 3.3V Active Analog
Attenuator
Reducing a signal’s amplitude from a 5V to 3.3V
system using an op amp.
The simplest method of converting a 5V analog
signal to a 3.3V analog signal is to use a
resistor divider with a ratio R1:R2 of 1.7:3.3.
However, there are a few problems with this.
Figure 16-2: Op Amp Attenuators
R1
6
1.7 x
5 +
R2
Under either of these conditions, an op amp
becomes necessary to buffer the signals.
The op amp circuit necessary is a unity gain
follower (see Figure 16-1).
7
3.3 x
1. The attenuator may be feeding a capacitive
load, creating an unintentional low pass filter.
2. The attenuator circuit may need to drive a
low-impedance load from a high-impedance
source.
-
(OR)
6
-
5 +
7
R1
1.7 x
R2
3.3 x
Figure 16-1: Unity Gain
6
5
-
7
+
This circuit will output the same voltage that is
applied to the input.
To convert the 5V signal down to a 3V signal,
we simply add the resistor attenuator.
Page 8-14-DS01146B
If the resistor divider is before the unity gain
follower, then the lowest possible impedance is
provided for the 3.3V circuits. Also, the op amp
can be powered from 3.3V, saving some power.
If the X is made very large, then power
consumed by the 5V side can be minimized.
If the attenuator is added after the unity gain
follower, then the highest possible impedance is
presented to the 5V source. The op amp must
be powered from 5V and the impedance at the
3V side will depend upon the value of R1||R2.
© 2009 Microchip Technology Inc.
3V Tips ‘n Tricks
TIP #175V → 3V Analog Limiter
When moving a 5V signal down to a 3.3V
system, it is sometimes possible to use the
attenuation as gain. If the desired signal is less
than 5V, then attaching that signal to a 3.3V
ADC will result in larger conversion values. The
danger is when the signal runs to the 5V rail.
A method is therefore required to control the
out-of-range voltages while leaving the in-range
voltages unaffected. Three ways to accomplish
this will be discussed here.
1. Using a diode to clamp the overvoltage to the
3.3V supply.
2. Using a Zener diode to clamp the voltage to
any desired limit.
3. Using an op amp with a diode to perform a
precision clamp.
The simplest method to perform the overvoltage
clamp is identical to the simple method of
interfacing a 5V digital signal to the 3.3V digital
signals. A resistor and a diode are used to direct
excess current into the 3.3V supply. The resistor
must be sized to protect the diode and the 3.3V
supply while not adversely affecting the analog
performance. If the impedance of the 3.3V
supply is too low, then this type of clamp can
cause the 3.3V supply voltage to increase. Even
if the 3.3V supply has a good low-impedance,
this type of clamp will allow the input signal to
add noise to the 3.3V supply when the diode is
conducting and if the frequency is high enough,
even when the diode is not conducting due to
the parasitic capacitance across the diode.
Figure 17-1: Diode Clamp
+3.3V
D1
VIN
VOUT
R1
VOUT = 3.3V + VF if VIN > 3.3V + VF
VOUT = VIN if VIN ≤ 3.3V + VF
VF is the forward drop of the diode.
To prevent the input signal from affecting the
supply or to make the input more robust to
larger transients, a variation is to use a Zener
diode. The Zener diode is slower than the fast
signal diode typically used in the first circuit.
However, they are generally more robust and do
not rely on the characteristics of the power
supply to perform the clamping. The amount of
clamping they provide is dependant upon the
current through the diode. This is set by the
value of R1. R1 may not be required if the
output impedance of the Vin source is
sufficiently large.
Figure 17-2: Zener Clamp
VIN
VOUT
R1
D1
VOUT = VBR if VIN > VBR
VOUT = VIN if VIN ≤ VBR
VBR is the reverse breakdown voltage of
the Zener diode.
© 2009 Microchip Technology Inc.
DS01146B-Page 8-15
3V Tips ‘n Tricks
If a more precise overvoltage clamp is required
that does not rely upon the supply, then an op
amp can be employed to create a precision
diode. In Figure 17-3, such a circuit is shown.
The op amp compensates for the forward
drop in the diode and causes the voltage to be
clamped at exactly the voltage supplied on the
non-inverting input to the op amp. The op amp
can be powered from 3.3V if it is rail-to-rail.
Figure 17-3: Precision Diode Clamp
6
When driving bipolar transistors, the amount of
base current “drive” and forward current gain
(B/hfe) will determine how much current
the transistor can sink. When driven by a
microcontroller I/O port, the base drive current
is calculated using the port voltage and the port
current limit (typically 20 mA). When using 3.3V
technology, smaller value base current limiting
resistors should be used to ensure sufficient
base drive to saturate the transistor.
Figure 18-1: Driving Bipolar Transistors
Using Microcontroller I/O Port
-
5
+
+3.3V
TIP #18Driving Bipolar Transistors
VLOAD
D1
+
R1
VOUT
+VDD
-
VIN
RBASE
hFE (Forward Gain)
VOUT = 3.3V if VIN > 3.3V
VOUT = VIN if VIN ≤ 3.3V
Because the clamping is performed by the op
amp, there is no affect on the power supply. The
impedance presented to the low voltage circuit
is not improved by the op amp, it remains R1 in
addition to the source circuit impedance.
Page 8-16-DS01146B
RLOAD
VBE Forward Drop
The value of Rbase will depend on the
microcontroller supply voltage. Equation 18-1
describes how to calculate Rbase.
© 2009 Microchip Technology Inc.
3V Tips ‘n Tricks
Table 18-1: Bipolar Transistor DC
Specifications
Characteristic
Sym
OFF CHARACTERISTICS
Collector-Base
V(br)cbo
Breakdown
Voltage
3V Technology Example
Test
Condition
Min
Max
Unit
60
–
V
Ic = 50 µA,
Ie = 0
Collector-Emitter
Breakdown
Voltage
V(br)ceo
50
–
V
Ic = 1.0
mA,
Ib = 0
Emitter-Base
Breakdown
Voltage
V(br)ebo
7.0
–
V
Ie = 50 µA,
Ic = 0
Collector Cutoff
Current
Icbo
–
100
nA
Vcb = 60V
Emitter Cutoff
Current
Iebo
–
100
nA
Veb = 7.0V
120
180
270
270
390
560
–
Vce = 6.0V,
Ic = 1.0 mA
–
0.4
V
Ic = 50 mA,
Ib = 5.0 mA
ON CHARACTERISTICS
DC Current Gain
hfe
Collector-Emitter
Saturation Voltage
Vce(sat)
Vdd = +3V, Vload = +40V, Rload = 400Ω,
hfe min. = 180, Vbe = 0.7V
Rbase = 4.14 kΩ, I/O port current = 556 µA
5V Technology Example
Vdd = +5V, Vload = +40V, Rload = 400Ω,
hfe min. = 180, Vbe = 0.7V
Rbase = 7.74 kΩ, I/O port current = 556 µA
For both examples, it is good practice to
increase base current for margin. Driving the
base with 1 mA to 2 mA would ensure saturation
at the expense of increasing the input power
consumption.
When using bipolar transistors as switches
to turn on and off loads controlled by the
microcontroller I/O port pin, use the minimum
hfe specification and margin to ensure complete
device saturation.
Equation 18-1: Calculating the Base Resistor
Value
Rbase = (Vdd - Vbe) x hfe x Rload
Vload
© 2009 Microchip Technology Inc.
DS01146B-Page 8-17
3V Tips ‘n Tricks
TIP #19Driving N-Channel MOSFET
Transistors
Care must be taken when selecting an external
N-Channel MOSFET for use with a 3.3V
microcontroller. The MOSFET gate threshold
voltage is an indication of the device’s capability
to completely saturate. For 3.3V applications,
select MOSFETs that have an ON resistance
rating for gate drive of 3V or less. For example,
a FET that is rated for 250 µA of drain current
with 1V applied from gate-to-source is not
necessarily going to deliver satisfactory results
for 100 mA load with a 3.3V drive. When
switching from 5V to 3V technology, review the
gate-to-source threshold and ON resistance
characteristics very carefully as shown in Figure
19-1. A small decrease in gate drive voltage can
significantly reduce drain current.
Figure 19-1: Drain Current Capability Versus
Gate to Source Voltage
ID
Low threshold devices commonly exist for
MOSFETs with drain-to-source voltages rated
below 30V. MOSFETs with drain-to-source
voltages above 30V typically have higher gate
thresholds (VT).
Table 19-1:Rds(ON) and Vgs(th)
Specifications for IRF7467
Rds(on)
Vgs(th)
Gate
Threshold
Voltage
9.4
12
–
10.6
13.5
–
17
35
0.6
–
2.0
Vgs = 10V,
Id = 11A
mΩ
Vgs = 4.5V,
Id = 9.0A
Vgs = 2.8V,
Id = 5.5A
V
Vds = Vgs,
Id = 250 µA
As shown in Table 19-1, the threshold voltage
for this 30V, N-Channel MOSFET switch is 0.6V.
The resistance rating for this MOSFET is 35 mΩ
with 2.8V applied gate, as a result, this device is
well suited for 3.3V applications.
Table 19-2:Rds(ON) and Vgs(th)
Specifications for IRF7201
Rds(on)
0
Static Drainto-Source
On-Resistance
–
0
VT
VGS
3.3V 5V
Vgs(th)
Static Drainto-Source
On-Resistance
Gate
Threshold
Voltage
–
–
0.030
–
–
0.050
1.0
–
–
Ω
V
Vgs = 10V,
Id = 7.3A
Vgs = 4.5V,
Id = 3.7A
Vds = Vgs,
Id = 250 µA
For the IRF7201 data sheet specifications,
the gate threshold voltage is specified as a
1.0V minimum. This does not mean the device
can be used to switch current with a 1.0V
gate-to-source voltage as there is no RDS(ON)
specification for Vgs(th) values below 4.5V.
This device is not recommended for 3.3V drive
applications that require low switch resistance
but can be used for 5V drive applications.
Page 8-18-DS01146B
© 2009 Microchip Technology Inc.
WORLDWIDE SALES AND SERVICE
AMERICAS
ASIA/PACIFIC
ASIA/PACIFIC
EUROPE
Corporate Office
2355 West Chandler Blvd.
Chandler, AZ 85224-6199
Tel: 480-792-7200
Fax: 480-792-7277
Technical Support:
http://support.microchip.com
Web Address:
www.microchip.com
Asia Pacific Office
Suites 3707-14, 37th Floor
Tower 6, The Gateway
Harbour City, Kowloon
Hong Kong
Tel: 852-2401-1200
Fax: 852-2401-3431
India - Bangalore
Tel: 91-80-3090-4444
Fax: 91-80-3090-4080
India - New Delhi
Tel: 91-11-4160-8631
Fax: 91-11-4160-8632
Austria - Wels
Tel: 43-7242-2244-39
Fax: 43-7242-2244-393
Denmark - Copenhagen
Tel: 45-4450-2828
Fax: 45-4485-2829
India - Pune
Tel: 91-20-2566-1512
Fax: 91-20-2566-1513
France - Paris
Tel: 33-1-69-53-63-20
Fax: 33-1-69-30-90-79
Japan - Yokohama
Tel: 81-45-471- 6166
Fax: 81-45-471-6122
Germany - Munich
Tel: 49-89-627-144-0
Fax: 49-89-627-144-44
Atlanta
Duluth, GA
Tel: 678-957-9614
Fax: 678-957-1455
Boston
Westborough, MA
Tel: 774-760-0087
Fax: 774-760-0088
Chicago
Itasca, IL
Tel: 630-285-0071
Fax: 630-285-0075
Cleveland
Independence, OH
Tel: 216-447-0464
Fax: 216-447-0643
Dallas
Addison, TX
Tel: 972-818-7423
Fax: 972-818-2924
Detroit
Farmington Hills, MI
Tel: 248-538-2250
Fax: 248-538-2260
Kokomo
Kokomo, IN
Tel: 765-864-8360
Fax: 765-864-8387
Los Angeles
Mission Viejo, CA
Tel: 949-462-9523
Fax: 949-462-9608
Santa Clara
Santa Clara, CA
Tel: 408-961-6444
Fax: 408-961-6445
Toronto
Mississauga, Ontario,
Canada
Tel: 905-673-0699
Fax: 905-673-6509
Australia - Sydney
Tel: 61-2-9868-6733
Fax: 61-2-9868-6755
China - Beijing
Tel: 86-10-8528-2100
Fax: 86-10-8528-2104
China - Chengdu
Tel: 86-28-8665-5511
Fax: 86-28-8665-7889
Korea - Daegu
Tel: 82-53-744-4301
Fax: 82-53-744-4302
China - Hong Kong SAR
Tel: 852-2401-1200
Fax: 852-2401-3431
Korea - Seoul
Tel: 82-2-554-7200
Fax: 82-2-558-5932 or
82-2-558-5934
China - Nanjing
Tel: 86-25-8473-2460
Fax: 86-25-8473-2470
Malaysia - Kuala Lumpur
Tel: 60-3-6201-9857
Fax: 60-3-6201-9859
China - Qingdao
Tel: 86-532-8502-7355
Fax: 86-532-8502-7205
Malaysia - Penang
Tel: 60-4-227-8870
Fax: 60-4-227-4068
China - Shanghai
Tel: 86-21-5407-5533
Fax: 86-21-5407-5066
Philippines - Manila
Tel: 63-2-634-9065
Fax: 63-2-634-9069
China - Shenyang
Tel: 86-24-2334-2829
Fax: 86-24-2334-2393
Singapore
Tel: 65-6334-8870
Fax: 65-6334-8850
China - Shenzhen
Tel: 86-755-8203-2660
Fax: 86-755-8203-1760
Taiwan - Hsin Chu
Tel: 886-3-6578-300
Fax: 886-3-6578-370
China - Wuhan
Tel: 86-27-5980-5300
Fax: 86-27-5980-5118
Taiwan - Kaohsiung
Tel: 886-7-536-4818
Fax: 886-7-536-4803
China - Xiamen
Tel: 86-592-2388138
Fax: 86-592-2388130
Taiwan - Taipei
Tel: 886-2-2500-6610
Fax: 886-2-2508-0102
China - Xian
Tel: 86-29-8833-7252
Fax: 86-29-8833-7256
Thailand - Bangkok
Tel: 66-2-694-1351
Fax: 66-2-694-1350
Italy - Milan
Tel: 39-0331-742611
Fax: 39-0331-466781
Netherlands - Drunen
Tel: 31-416-690399
Fax: 31-416-690340
Spain - Madrid
Tel: 34-91-708-08-90
Fax: 34-91-708-08-91
UK - Wokingham
Tel: 44-118-921-5869
Fax: 44-118-921-5820
China - Zhuhai
Tel: 86-756-3210040
Fax: 86-756-3210049
03/26/09
DS01146B
© 2009 Microchip Technology Inc.