tips using small nr of input

Upload: zhuzhu2010

Post on 29-May-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 Tips Using Small Nr of Input

    1/44

    8-pin FLASH

    PIC Microcontrollers

    Outperform the Competition

    Tips n Tricks

  • 8/9/2019 Tips Using Small Nr of Input

    2/44

  • 8/9/2019 Tips Using Small Nr of Input

    3/44

    =OMMP=j=q=fK apQMMQM_J~=

    Tips n Tricks With Hardware

    TIP #1 Dual Speed RC Oscillator ............................ 2

    TIP #2 Input/Output Multiplexing.............................. 3

    TIP #3 Read Three States From One Pin ................ 4

    TIP #4 Reading DIP Switches.................................. 5

    TIP #5 Scanning Many Keys With One Input........... 6

    TIP #6 Scanning Many Keys and

    Wake-up From Sleep ................................... 8

    TIP #7 8x8 Keyboard with 1 Input...........................10

    TIP #8 One Pin Power/Data.................................... 11

    TIP #9 Decode Keys and ID Settings .....................12

    TIP #10 Generating High Voltages .........................13

    TIP #11 VDD Self Starting Circuit.............................14

    TIP #12 Using PIC MCU A/D For Smart

    Current Limiter...........................................15

    TIP #13 Reading A Sensor With Higher

    Accuracy....................................................16

    TIP #13 Reading A Sensor With Higher

    Accuracy RC Timing Method..................17

    TIP #13 Reading A Sensor With Higher

    Accuracy Charge Balancing Method ......20

    TIP #13 Reading A Sensor With Higher

    Accuracy A/D Method.............................22

    TIP #14 Delta Sigma Converter ..............................24

    Table of Contents

    Tips n Tricks

  • 8/9/2019 Tips Using Small Nr of Input

    4/44

    Tips n Tricks

    apQMMQM_J~= =OMMP=j=q=fK

    Tips 'n Tricks With Software

    TIP #15 Delay Techniques ......................................28

    TIP #16 Optimizing Destinations.............................30

    TIP #17 Conditional Bit Set/Clear ...........................31

    TIP #18 Swap File Register with W ........................33

    TIP #19 Bit Shifting Using Carry Bit ........................34

  • 8/9/2019 Tips Using Small Nr of Input

    5/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=N

    TIPS 'N TRICKS WITH HARDWARE

    Microchip continues to provide innovative

    products that are smaller, faster, easier to use andmore reliable. The 8-pin FLASH PICmicromicrocontrollers (MCU) are used in an wide rangeof everyday products, from toothbrushes, hairdryers and rice cookers to industrial, automotiveand medical products.

    The PIC12F629/675 MCUs merge all theadvantages of the PICmicro MCU architecture andthe flexibility of FLASH program memory into an8-pin package. They provide the features andintelligence not previously available due to costand board space limitations. Features include a14-bit instruction set, small footprint package, awide operating voltage of 2.0 to 5.5 volts, aninternal programmable 4 MHz oscillator, on-boardEEPROM data memory, on-chip voltage referenceand up to 4 channels of 10-bit A/D. The flexibility ofFLASH and an excellent development tool suite,including a low-cost In-Circuit Debugger, In-Circuit

    Serial Programming and MPLAB

    ICE 2000emulation, make these devices ideal for just aboutany embedded control application.

    The following series of Tips'n Tricks can beapplied to a variety of applications to help makethe most of the 8-pin dynamics.

  • 8/9/2019 Tips Using Small Nr of Input

    6/44

    Tips n Tricks

    apQMMQM_J~=O =OMMP=j=q=fK

    TIP #1 Dual Speed RC Oscillator

    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 oscillatormode depends on resistance and capacitance onOSC1 pin. Resistance is changed by the outputvoltage on GP0. GP0 output '1' puts R2 in parallelwith R1 reduces OSC1 resistance and increasesOSC1 frequency. GP0 as an input increases theOSC1 resistance by minimizing current flowthrough R2, and decreases frequency and power

    consumption.Summary:

    GP0 = Input: Slow speed for low current

    GP0 = Output high: High speed for fast processing

    PIC12F6XX

    OSC1

    GP0

    +5V

    R2R1

    C

  • 8/9/2019 Tips Using Small Nr of Input

    7/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=P

    TIP #2 Input/Output Multiplexing

    Individual diodes and some combination of diodes

    can be enabled by driving I/Os high and low orswitching to inputs (Z). The number of diodes (D)that can be controlled depends on the number ofI/Os (GP) used.

    The equation is: D = GP x (GP - 1).

    Example Six LEDs on three I/O pins

    GPx LEDs

    0 1 2

    0 0 0

    0 1 Z

    1 0 Z

    Z 0 1

    Z 1 0

    0 Z 1

    1 Z 0

    0 0 1

    0 1 0

    0 1 11 0 0

    1 0 1

    1 1 0

    1 1 1

    1 2 3 4 5 6

    0 0 0 0 0 0

    1 0 0 0 0 0

    0 1 0 0 0 0

    0 0 1 0 0 0

    0 0 0 1 0 0

    0 0 0 0 1 0

    0 0 0 0 0 1

    0 0 1 0 1 0

    1 0 0 1 0 0

    1 0 0 0 1 00 1 0 0 0 1

    0 1 1 0 0 0

    0 0 0 1 0 1

    0 0 0 0 0 0

    PIC12F6XX

    1 2 5

    43

    6

    GP0

    GP1

    GP2

  • 8/9/2019 Tips Using Small Nr of Input

    8/44

    Tips n Tricks

    apQMMQM_J~=Q =OMMP=j=q=fK

    TIP #3 Read Three States From One Pin

    To check state Z:

    Drive output pin high

    Set to Input

    Read 1

    Drive output pin low

    Set to Input

    Read 0

    To check state 0:

    Read 0 on pin

    To check state 1:

    Read 1 on pin

    Jumper has three possible states: not connected,link 1 and link 0. The capacitor will charge anddischarge depending on the I/O output voltage

    allowing the "not connected" state. Softwareshould check the "not connected" state first bydriving I/O high, reading 1 and driving I/O low andreading 0. The "Link 1" and "Link 0" states are readdirectly.

    State Link0 Link1

    0 closed open

    1 open closed

    NC open open

    PICI/O

    5V

    0V

    Link 0

    Link 1

  • 8/9/2019 Tips Using Small Nr of Input

    9/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=R

    TIP #4 Reading DIP Switches

    The input of a timer

    can be used to testwhich switch(s) isclosed. The input ofTimer 1 is held highwith a pull-upresistor.

    Sequentially, eachswitch I/O is set toinput and Timer 1 ischecked for anincrement indicatingthe switch is closed.

    Each bit in the DP register represents itscorresponding switch position. By setting Timer 1to FFFFh and enabling its interrupt, an incrementwill cause a rollover and generate an interrupt.This will simplify the software by eliminating the bittest 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).

    PIC12F6XX

    GP0

    GP1

    GP2

    GP3

    GP5/T1CKI

    10K

    VDD

    GP4Data I/O

    movlw b'11111111'

    movwf TRISIOmovwf DIP

    movlw b'00000111'movwf T1CON

    movlw b'11111110'

    movwf Maskclrf GPIO

    LOOPclrf TMR1L

    movf Mask,W

    movwf TRISIObtfsc TMR1L,0

    andwf DIP,F

    bsf STATUS,Crlf Mask,F

    btfsc Mask,4

    goto Loopretlw 0

  • 8/9/2019 Tips Using Small Nr of Input

    10/44

    Tips n Tricks

    apQMMQM_J~=S =OMMP=j=q=fK

    TIP #5 Scanning Many Keys With

    One Input

    The time required to charge a capacitor dependson resistance between VDD and capacitor. When abutton is pressed, VDD is supplied to a differentpoint in the resistor ladder. The resistancebetween VDD and the capacitor is reduced, whichreduces the charge time of the capacitor. A timer

    is used with a comparator or changing digital inputto measure the capacitor charge time. The chargetime is used to determine which button is pressed.

    Software sequence:

    1. Configure GP2 to output a low voltage todischarge capacitor through I/O resistor.

    2. Configure GP2 as one comparator input andCVREF as the other.

    3. Use a timer to measure when the comparatortrips. If the time measured is greater than themaximum allowed time, then repeat; otherwisedetermine which button is pressed.

  • 8/9/2019 Tips Using Small Nr of Input

    11/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=T

    TIP #5 Scanning Many Keys With

    One Input (Cont.)

    When a key is pressed, the voltage divider networkchanges the RC ramp rate.

    See AN512 Implementing Ohmmeter/Temperature Sensorfor code ideas.

    PIC12F6XXGP0

    GP1

    GP2

    GP4

    GP5

    GP3

    16Resistors

    220 Ohm

    R

    R

    R

    R

  • 8/9/2019 Tips Using Small Nr of Input

    12/44

    Tips n Tricks

    apQMMQM_J~=U =OMMP=j=q=fK

    TIP #6 Scanning Many Keys and

    Wake-up From Sleep

    An additional I/O can be added to wake the partwhen a button is pressed. Prior to sleep, configureGP1 as an input with interrupt-on-change enabledand GP2 to output high. The pull-down resistorholds GP1 low until a button is pressed. GP1 isthen pulled high via GP2 and VDD generating an

    interrupt. After wake-up, GP2 is configured tooutput low to discharge the capacitor through the220 Ohm resistor. GP1 is set to output high andGP2 is set to an input to measure the capacitorcharge time.

    GP1 pin connected to key common

    Enable wake-up on port change Set GP1 as input and GP2 high prior to sleep

    If key is pressed the PIC MCU wakes up, GP2must be set low to discharge capacitor

    Set GP1 high upon wake-up to scan keystroke

  • 8/9/2019 Tips Using Small Nr of Input

    13/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=V

    TIP #6 Scanning Many Keys and

    Wake-up From Sleep (Cont.)

    VDD

    PIC12F6XX

    GP0

    GP1

    GP2

    GP4

    GP5

    GP3

    16Resistors

    220 Ohm

    R

    R

    R

    R

    100R

  • 8/9/2019 Tips Using Small Nr of Input

    14/44

    Tips n Tricks

    apQMMQM_J~=NM =OMMP=j=q=fK

    TIP #7 4x4 Keyboard with 1 Input

    By carefully selecting the resistor values, each

    button generates a unique voltage. This voltage ismeasured by the A/D to determine which button ispressed. Higher precision resistors should beused to maximize voltage uniqueness. The A/Dwill read near 0 when no buttons are pressed.

    VDD

    PIC12F6XX

    GP0

  • 8/9/2019 Tips Using Small Nr of Input

    15/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=NN

    TIP #8 One Pin Power/Data

    A single I/O can be used for both a single-direction

    communication and the power source for anothermicrocontroller. The I/O line is held high by thepull-up resistor connected to VDD. The senderuses a pull-down transistor to pull the data line lowor disables the transistor to allow the pull-up toraise it to send data to the receiver. VDD is supplied

    to the sender through the data line. The capacitorstabilizes the sender's VDD and a diode preventsthe capacitor from discharging through the I/O linewhile it is low. Note that the VDD of the sender is adiode-drop lower than the receiver.

    Receiver

    VDD - 0.7VVDDVDD

    GP0 GP0

    Sender

  • 8/9/2019 Tips Using Small Nr of Input

    16/44

    Tips n Tricks

    apQMMQM_J~=NO =OMMP=j=q=fK

    TIP #9 Decode Keys and ID Settings

    Buttons and jumpers can share I/O's by using

    another I/O to select which one is read. Bothbuttons and jumpers are tied to a shared pull-downresistor. Therefore, they will read as '0' unless abutton is pressed or a jumper is connected. Eachinput (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' onits assigned I/O or '0' if its not connected. WithGP4 output low, a pressed button will be read as'1' on its assigned I/O and '0' otherwise.

    When GP4 = 1 and no keys are pressed, readID setting

    When GP4 = 0, read the switch buttons

    VDD

    GP0

    GP1

    GP2

    GP3

    GP4

  • 8/9/2019 Tips Using Small Nr of Input

    17/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=NP

    TIP #10 Generating High Voltages

    Voltages greater than VDD can be generated usinga toggling I/O. PIC MCUs CLKOUT/OSC2 pintoggles at one quarter the frequency of OSC1when in external RC oscillator mode. When OSC2is low, the VDD diode is forward biased andconducts current, thereby charging Cpump. AfterOSC2 is high, the other diode is forward biased,

    moving the charge to Cfilter. The result is a chargeequal to twice the VDDminus two diode drops. Thiscan be used with a PWM, a toggling I/O or othertoggling pin.

    PIC12F6XX

    w/RC

    CLKOUT

    Cpump

    VDD

    Cfilter

    CLKOUT

    VOUT max = 2 * VDD - 2 * Vdiode

  • 8/9/2019 Tips Using Small Nr of Input

    18/44

    Tips n Tricks

    apQMMQM_J~=NQ =OMMP=j=q=fK

    TIP #11 VDD Self Starting Circuit

    Building on the previous topic, the same charge

    pump can be used by the MCU to supply its ownVDD. Before the switch is pressed, VBAT has powerand the VDD points are connected together butunpowered. When the button is pressed, power issupplied to VDD and the MCUs CLKOUT (inexternal RC oscillator mode) begins toggle. The

    voltage generated by the charge pump turns onthe FET allowing VDD to remain powered. Topower down the MCU, execute a SLEEPinstruction. This allows the MCU to switch off itspower source via software.

    Advantages:

    PIC

    MCU leakage current nearly 0 Low cost (uses n-channel FET)

    Reliable

    No additional I/O pins required

    PIC12F6XX

    VDD

    CLKOUT

    VDD

    VDD

    VDD

    VBAT

  • 8/9/2019 Tips Using Small Nr of Input

    19/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=NR

    TIP #12 Using PIC MCU A/D For Smart

    Current Limiter

    Detect current through low side sense resistor

    Optional peak filter capacitor

    Varying levels of overcurrent response can berealized in software

    By adding a resistor (Rsense) in series with amotor, the A/D can be used to measure in-rushcurrent, provide current limiting, over-currentrecovery or work as a smart circuit breaker. The10K resistor limits the analog channel current anddoes not violate the source impedance limit of theA/D.

    W

    PIC12F6XX

    10K

    AN0

    Rsense

    Load or Motor

  • 8/9/2019 Tips Using Small Nr of Input

    20/44

  • 8/9/2019 Tips Using Small Nr of Input

    21/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=NT

    TIP #13 Reading A Sensor With Higher

    Accuracy RC Timing Method

    RC Timing Method:

    Simple RC step responseVc(t) = VDD * (1 - e -t/(RC))t = -RC ln(1 - Vth/VDD)Vth/VDD is constantR2 = (t2/t1) * R1

    A reference resistor can be used to improve the

    accuracy of an analog sensor reading. In thisdiagram, the charge time of a resistor/capacitorcombination is measured using a timer and a portinput or comparator input switches from a '0' to '1'.The R1 curve uses a reference resistor and the R2curve uses the sensor. The charge time of the R1curve is known and can be used to calibrate theunknown sensor reading, R2. This reduces theaffects of temperature, component tolerance andnoise while reading the sensor.

    Time

    Vc(t)

    Vth

    t = 0 t = t1 t = t2

    R1R2

  • 8/9/2019 Tips Using Small Nr of Input

    22/44

    Tips n Tricks

    apQMMQM_J~=NU =OMMP=j=q=fK

    TIP #13 Reading A Sensor With Higher

    Accuracy RC Timing Method

    (Cont.)Application Notes:AN512 Implementing Ohmmeter/TemperatureSensor

    AN611 Resistance and Capacitance Meter Usinga PIC16C622

    Here is the schematic and software flow for usinga reference resistor to improve the accuracy of ananalog sensor reading. The reference resistor(Rref) and sensor (Rsen) are assigned an I/O andshare a common capacitor. GP0 is used todischarge the capacitor and represents the

    capacitor voltage.Through software, a timer is used to measurewhen GP0 switches from a '0' to a '1' for the sensorand reference measurements. Any differencemeasured between the reference measurementand its calibrated measurement is used to adjustthe sensor reading, resulting in a more accuratemeasurement.

    The comparator and comparator reference on thePIC12F629/675 can be used instead of a port pinfor a more accurate measurement. Polypropylenecapacitors are very stable and beneficial in thistype of application.

  • 8/9/2019 Tips Using Small Nr of Input

    23/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=NV

    TIP #13 Reading A Sensor With Higher

    Accuracy RC Timing Method

    (Cont.)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 output6. Measure tRref (GP0 changes to 1)

    7. Use film polypropylene capacitor

    8. Rth = x Rref tRsentRref

    Other alternatives: voltage comparator in thePIC12F6XX to measure capacitor voltage on GP0.

    PIC12F629

    GP0

    GP1

    GP2

    Rref

    Rsen

  • 8/9/2019 Tips Using Small Nr of Input

    24/44

    Tips n Tricks

    apQMMQM_J~=OM =OMMP=j=q=fK

    TIP #13 Reading A Sensor With Higher

    Accuracy Charge Balancing

    Method1. Sensor charges a capacitor

    2. Reference resistor discharges the capacitor

    3. Modulate reference resistor to maintainconstant average charge in the capacitor

    4. Use comparator to determine modulation

    To improve resolution beyond 10 or 12 bits, atechnique called "Charge Balancing" can be use.The basic concept is for the MCU to maintain aconstant voltage on a capacitor by either allowingthe charge to build through a sensor or dischargethrough a reference resistor. A timer is used to

    sample the capacitor voltage on regular intervalsuntil a predetermined number of samples arecounted. By counting the number of times thecapacitor voltage is over an arbitrary threshold, thesensor voltage is determined. The comparator andcomparator voltage reference (CVref) on thePIC12F629/675 are ideal for this application.

  • 8/9/2019 Tips Using Small Nr of Input

    25/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=ON

    TIP #13 Reading A Sensor With Higher

    Accuracy Charge Balancing

    Method (Cont.)1. GP1 average voltage = CVref

    2. Time base as sampling rate

    3. At the end of each time base period:

    - If GP1 > CVref, then GP2 Output Low

    - If GP1 < CVref, then GP2 Input mode

    4. Accumulate the GP2 lows over many samples

    5. Number of samples determines resolution

    6. Number of GP2 lows determine effective dutycycle of Rref

    PIC12F6XX

    Rsen

    GP1

    GP2

    T1GRref

    VDD

    +

    _

    CVref

    COUT

  • 8/9/2019 Tips Using Small Nr of Input

    26/44

    Tips n Tricks

    apQMMQM_J~=OO =OMMP=j=q=fK

    TIP #13 Reading A Sensor With Higher

    Accuracy A/D Method

    NTC (Negative Temperature Coefficient) sensorshave a non-linear response to temperaturechanges. As the temperature drops, the amountthe resistance changes becomes less and less.Such sensors have a limited useful range becausethe resolution becomes smaller than the A/D

    resolution as the temperature drops. By changingthe voltage divider of the Rsen, the temperaturerange can be expanded.

    To select the higher temperature range, GP1outputs '1' and GP2 is set as an input. For thelower range, GP2 outputs '1' and GP1 isconfigured as an input. The lower range willincrease the amount the sensor voltage changesas the temperature drops to allow a larger usablesensor range.

    Summary:

    High range: GP1 output '1' and GP2 input

    Low range: GP1 input and GP2 output '1'

  • 8/9/2019 Tips Using Small Nr of Input

    27/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=OP

    TIP #13 Reading A Sensor With Higher

    Accuracy A/D Method (Cont.)

    1. 10K and 100K resistors are used to set therange

    2. Vref for A/D = VDD

    3. Rth calculation is independent of VDD

    4. Count = Rsen/(Rsen+Rref) x 255

    5. Don't forget to allow acquisition time for the

    A/D

    PIC12F675

    AN0 (A/D Input)

    GP1

    GP2

    100K

    10K

    Rsen

  • 8/9/2019 Tips Using Small Nr of Input

    28/44

    Tips n Tricks

    apQMMQM_J~=OQ =OMMP=j=q=fK

    TIP #14 Delta Sigma Converter

    The charge on the capacitor on GP1 is maintained

    about equal to the CVref by the MCU monitoringCOUT and switching GP2 from input mode oroutput low appropriately. A timer is used to samplethe COUT bit on a periodic basis. Each time GP2is driven low, a counter is incremented. Thiscounter value corresponds to the input voltage.

    To minimize the affects of external componenttolerances, temperature, etc., the circuit can becalibrated. Apply a known voltage to the input andallow the microcontroller to count samples until theexpected result is calculated. By taking the samenumber of samples for subsequentmeasurements, they become calibratedmeasurements.

  • 8/9/2019 Tips Using Small Nr of Input

    29/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=OR

    TIP #14 Delta Sigma Converter (Cont.)

    1. GP1 average voltage = CVref

    2. Time base as sampling rate

    3. At the end of each time base period:- If GP1 > CVref, then GP2 Output Low

    - If GP1 < CVref, then GP2 Output High

    4. Accumulate the GP2 lows over many samples

    5. Number of samples determines resolution

    COUT

    VIN

    CVREF

    PIC12F6XX

    GP1

    GP2

    +

    -

  • 8/9/2019 Tips Using Small Nr of Input

    30/44

    Tips n Tricks

    apQMMQM_J~=OS =OMMP=j=q=fK

    NOTES:

  • 8/9/2019 Tips Using Small Nr of Input

    31/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=OT

    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 theMCU cost. Optimizing the code helps to avoidbuying more memory than needed. Here are someideas that can help reduce code size.

  • 8/9/2019 Tips Using Small Nr of Input

    32/44

    Tips n Tricks

    apQMMQM_J~=OU =OMMP=j=q=fK

    TIP #15 Delay Techniques

    Use GOTO "next instruction" instead of two

    NOPs. Use CALL Rtrn as quad, 1 instruction NOP

    (where "Rtrn" is the exit label from existingsubroutine).

    MCUs are commonly used to interface with theoutside world by means of a data bus, LEDs,buttons, latches, etc. Because the MCU runs at afixed frequency, it will often need delay routines tomeet setup/hold times of other devices, pause fora handshake or decrease the data rate for ashared bus.

    Longer delays are well-suited for the DECFSZ and

    INCFSZ instructions where a variable isdecremented or incremented until it reaches zerowhen a conditional jump is executed. For shorterdelays of a few cycles, here a few ideas todecrease code size.

    NOPNOP

    GOTO $+1

    CALL Rtrn ;1 instruction, 4 cycles

    Rtrn RETURN. . .

    ;2 instructions, 2 cycles

    ;1 instruction, 2 cycles

  • 8/9/2019 Tips Using Small Nr of Input

    33/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=OV

    TIP #15 Delay Techniques (Cont.)

    For a two cycle delay, it is common to use two

    NOP instructions which uses two programmemory locations. The same result can beachieved by using goto $+1. The $ representsthe current program counter value in MPASM.When this instruction is encountered, the MCU willjump to the next memory location. This is what it

    would have done if two NOPs were used but sincethe goto instruction uses two instruction cycles toexecute, a two cycle delay was created. Thiscreated a two cycle delay using only one locationof program memory.

    To create a four cycle delay, add a label to anexisting RETURN instruction in the code. In thisexample, the label Rtrn was added to theRETURN of subroutine that already existedsomewhere in the code. When executing CALLRtrn, the MCU delays two instruction cycles toexecute the CALL and two more to execute theRETURN. Instead of using four NOP

    instructions to create a four cycle delay, the sameresult was achieved by adding a single CALLinstruction.

  • 8/9/2019 Tips Using Small Nr of Input

    34/44

    Tips n Tricks

    apQMMQM_J~=PM =OMMP=j=q=fK

    TIP #16 Optimizing Destinations

    Destination bit determines W for F for result

    Look at data movement and restructure

    Careful use of the destination bits in instructionscan save program memory. Here, register A andregister B are summed and the result is put into theA register. A destination option is available for

    logic and arithmetic operations. In the firstexample, the result of the ADDWF instruction isplaced in the working register. A MOVWFinstruction is used to move the result from theworking register to register A. In the secondexample, the ADDWF instruction uses thedestination bit to place the result into the A registersaving an instruction.

    Example: A + B A

    MOVF

    ADDWF

    MOVWF

    MOVF

    ADDWF

    A,W

    B,W

    A

    B,W

    A,F

    3 instructions 2 instructions

  • 8/9/2019 Tips Using Small Nr of Input

    35/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=PN

    TIP #17 Conditional Bit Set/Clear

    To move single bit of data from REGA to REGB

    Precondition REGB bit

    Test REGA bit and fix REGB if necessary

    One technique for moving one bit from the REGAregister to REGB is to perform bit tests. In the firstexample, the bit in REGA is tested using a BTFSS

    instruction. If the bit is clear, the BCF instruction isexecuted and clears the REGB bit, and if the bit isset, the instruction is skipped.The second bit testdetermines if the bit is set, and if so, will executethe BSF and set the REGB bit, otherwise theinstruction is skipped. This sequence requires fourinstructions.

    BTFSS

    BCF

    BTFSC

    BSF

    BCF

    BTFSC

    BSF

    REGA,2

    REGB,5

    REGA,2

    REGB,5

    REGB,5

    REGA,2

    REGB,5

    4 instructions 3 instructions

  • 8/9/2019 Tips Using Small Nr of Input

    36/44

    Tips n Tricks

    apQMMQM_J~=PO =OMMP=j=q=fK

    TIP #17 Conditional Bit Set/Clear (Cont.)

    A more efficient technique is to assume the bit in

    REGA is clear, and clear the REGB bit, and test ifthe REGA bit is clear. If so, the assumption wascorrect and the BSF instruction is skipped,otherwise the REGB bit is set. The sequence in thesecond example uses three instructions becauseone bit test was not needed.

    One important point is that the second examplewill create a two cycle glitch if REGB is a portoutputting a high. This is caused by the BCF andBTFSC instructions that will be executedregardless of the bit value in REGA.

  • 8/9/2019 Tips Using Small Nr of Input

    37/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=PP

    TIP #18 Swap File Register with W

    The following macro swaps the contents of W andREG without using a second register.

    Needs: 0 TEMP registers3 Instructions3 Tcy

    An efficient way of swapping the contents of aregister with the working register is to use threeXORWF instructions. It requires no temporary

    registers and three instructions. Heres anexample:

    W REG Instruction

    10101100 01011100 XORWF REG,F

    10101100 11110000 XORWF REG,W

    01011100 11110000 XORWF REG,F

    01011100 10101100 Result

    SWAPWF MACRO REG

    XORWF REG,F

    XORWF REG,W

    XORWF REG,F

    ENDM

  • 8/9/2019 Tips Using Small Nr of Input

    38/44

    Tips n Tricks

    apQMMQM_J~=PQ =OMMP=j=q=fK

    TIP #19 Bit Shifting Using Carry Bit

    Rotate a byte through carry without using RAM

    variable for loop count:

    Easily adapted to serial interface transmitroutines.

    Carry bit is cleared (except last cycle) and thecycle repeats until the zero bit sets indicatingthe end.

    bsfrlfbcfbtfscbsfbcfrlfmovfbtfssgoto

    LIST P=PIC12f629INCLUDE P12f629.INCbuffer

    STATUS,Cbuffer,fGPIO,DoutSTATUS,CGPIO,DoutSTATUS,Cbuffer,fbuffer,fSTATUS,ZSend_Loop

    equ 0x20

    ; Set 'end of loop' flag; Place first bit into C; precondition output; Check data 0 or 1 ?

    ; Clear data in C; Place next bit into C; Force Z bit; Exit?

  • 8/9/2019 Tips Using Small Nr of Input

    39/44

    Tips n Tricks

    =OMMP=j=q=fK apQMMQM_J~=PR

    NOTES:

  • 8/9/2019 Tips Using Small Nr of Input

    40/44

    Tips n Tricks

    apQMMQM_J~=PS =OMMP=j=q=fK

    NOTES:

  • 8/9/2019 Tips Using Small Nr of Input

    41/44

    =OMMP=j=q=fK apQMMQM_J~=PT

    Information contained in this publication regarding deviceapplications and the like is intended through suggestion only andmay be superseded by updates. It is your responsibility to ensure

    that your application meets with your specifications. No represen-tation or warranty is given and no liability is assumed by MicrochipTechnology Incorporated with respect to the accuracy or use ofsuch information, or infringement of patents or other intellectualproperty rights arising from such use or otherwise. Use ofMicrochips products as critical components in life support systemsis not authorized except with express written approval byMicrochip. No licenses are conveyed, implicitly or otherwise, underany intellectual property rights.

    The graphics in this document are for illustration only. Microchipreserves the right to modify the contents of its developmentsystems.

    Trademarks

    The Microchip name and logo, the Microchip logo, KEELOQ,MPLAB, PIC, PICmicro, PICSTART and PRO MATE are regis-tered trademarks of Microchip Technology Incorporated in theU.S.A. and other countries.

    FilterLab, microID, MXDEV, MXLAB, PICMASTER, SEEVAL andThe Embedded Control Solutions Company are registeredtrademarks of Microchip Technology Incorporated in the U.S.A.

    dsPIC, dsPICDEM.net, ECONOMONITOR, FanSense, FlexROM,fuzzyLAB, In-Circuit Serial Programming, ICSP, ICEPIC,microPort, Migratable Memory, MPASM, MPLIB, MPLINK,MPSIM, PICC, PICDEM, PICDEM.net, PICkit, rfPIC, Select Modeand Total Endurance are trademarks of Microchip Technology

    Incorporated in the U.S.A. and other countries.Serialized Quick Turn Programming (SQTP) is a service mark ofMicrochip Technology Incorporated in the U.S.A.

    All other trademarks mentioned herein are property of theirrespective companies.

    2003, Microchip Technology Incorporated. Printed in the U.S.A.,All Rights Reserved.

    Printed on recycled paper.

  • 8/9/2019 Tips Using Small Nr of Input

    42/44

    apQMMQM_J~=PU =OMMP=j=q=fK

    Worldwide Sales and Service

    AMERICAS

    Corporate OfficeTel: 480-792-7200Technical Support:480-792-7627

    Rocky MountainTel: 480-792-7966

    AtlantaTel: 770-640-0034

    BostonTel: 978-692-3848

    ChicagoTel: 630-285-0071

    DallasTel: 972-818-7423

    DetroitTel: 248-538-2250

    KokomoTel: 765-864-8360

    Los AngelesTel: 949-263-1888

    San JoseTel: 408-436-7950

    TorontoTel: 905-673-0699

    ASIA/PACIFIC

    AustraliaTel: 61-2-9868-6733

    China-BeijingTel:86-10-85282100

    China-Chengdu

    Tel: 86-28-86766200China-FuzhouTel: 86-591-7503506

    China-HongKong SARTel: 852-2401-1200

    China-ShanghaiTel: 86-21-6275-5700

    China-ShenzhenTel: 86-755-82901380

    China-QingdaoTel: 86-532-5027355

    IndiaTel: 91-80-2290061

    JapanTel: 81-45-471- 6166

    KoreaTel: 82-2-554-7200

    SingaporeTel: 65-6334-8870

    TaiwanTel: 886-2-2717-7175

    EUROPE

    AustriaTel: 43-7242-2244-399

    DenmarkTel: 45-4420-9895

    FranceTel: 33-1-69-53-63-20

    GermanyTel: 49-89-627-144-0

    ItalyTel: 39-039-65791-1

    United KingdomTel: 44-118-921-5869

    12/05/02

    *DS40040B*

    Microchip received QS-9000 quality system certification forits worldwide headquarters, design and wafer fabricationfacilities in Chandler and Tempe, Arizona in July 1999 andMountain View, California in March 2002. The Companysquality system processes and procedures are QS-9000compliant for its PICmicro8-bit MCUs, KEELOQcodehopping devices, Serial EEPROMs, microperipherals,non-volatile memory and analog products. In addition,Microchips quality system for the design and manufactureof development systems is ISO 9001 certified.

  • 8/9/2019 Tips Using Small Nr of Input

    43/44

  • 8/9/2019 Tips Using Small Nr of Input

    44/44

    Microchip Technology Inc.2355 W. Chandler Blvd. Chandler, AZ 85224 U.S.A.

    Phone: 480-792-7200 Fax: 480-792-9210

    www.microchip.com 2003, Microchip Technology Inc., 4/03 DS40040B