Designing with the 80C51BH - Application Note AP252 - 27006802

Embed Size (px)

Citation preview

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    1/28

    APPLICATION

    NOTE

    AP-252

    March 1985

    Designing With The 80C51BH

    TOM WILLIAMSONMCO APPLICATIONS ENGINEER

    Order Number 270068-002

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    2/28

    Information in this document is provided in connection with Intel products Intel assumes no liability whatsoev-er including infringement of any patent or copyright for sale and use of Intel products except as provided inIntels Terms and Conditions of Sale for such products

    Intel retains the right to make changes to these specifications at any time without notice MicrocomputerProducts may have minor variations to this specification known as errata

    Other brands and names are the property of their respective owners

    Since publication of documents referenced in this document registration of the Pentium OverDrive andiCOMP trademarks has been issued to Intel Corporation

    Contact your local Intel sales office or your distributor to obtain the latest specifications before placing yourproduct order

    Copies of documents which have an ordering number and are referenced in this document or other Intelliterature may be obtained from

    Intel CorporationPO Box 7641Mt Prospect IL 60056-7641

    or call 1-800-879-4683

    COPYRIGHT INTEL CORPORATION 1996

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    3/28

    DESIGNING WITH THE80C51BH

    CONTENTS PAGE

    CMOS EVOLVES 1

    WHAT IS CHMOS 1

    THE MCS-51 FAMILY IN CHMOS 1

    LATCHUP 2

    LOGIC LEVELS AND INTERFACINGPROBLEMS 2

    NOISE CONSIDERATIONS 2

    UNUSED PINS 3

    PULLUP RESISTORS 4

    PULLDOWN RESISTORS 4

    DRIVE CAPABILITY OF THEINTERNAL PULLUPS 5

    POWER CONSUMPTION 6

    Idle 7

    Power Down 7

    USING THE POWER DOWN MODE 8

    USING POWER MOSFETs TOCONTROL VCC 9

    BATTERY BACKUP SYSTEMS 9

    POWER SWITCHOVER CIRCUITS 11

    80C31BH a CHMOS EPROM 12

    SCANNING A KEYBOARD 13

    DRIVING AN LCD 16

    Using an LCD Driver 17

    RESONANT TRANSDUCERS 18

    Frequency Measurements 18

    Period Measurements 20

    Pulse Width Measurements 21

    HMOSCHMOSINTERCHANGEABILITY 21

    External Clock Drive 21

    Unused Pins 22

    Logic Levels 22

    Idle and Power Down 22

    REFERENCES 23

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    4/28

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    5/28

    AP-252

    CMOS EVOLVES

    The original CMOS logic families were the 4000-seriesand the 74C-series circuits The 74C-series circuits arefunctional equivalents to the corresponding numbered74-series TTL circuits but have CMOS logic levels and

    retain the other well known characteristics of CMOSlogic

    These characteristics are low power consumption highnoise immunity and slow speed The low power con-sumption is inherent to the nature of the CMOS circuitThe noise immunity is due partly to the CMOS logiclevels and partly to the slowness of the circuits Theslow speed is due to the technology used to constructthe transistors in the circuit

    The technology used is called metal-gate CMOS be-cause the transistor gates are formed by metal deposi-tion More importantly the gates are formed after thedrain and source regions have been defined and mustoverlap the source and drain somewhat to allow foralignment tolerances This overlap plus the relatively

    large size of the transistors themselves result in highelectrode capacitance and that is what limits the speedof the circuit

    High speed CMOS became feasible with the develop-ment of the self-aligning silicon gate technology In thisprocess polysilicon gates are deposited before thesource and drain regions are defined Then the sourceand drain regions are formed by ion implantation usingthe gate itself as a mask for the implantation This elim-inates most of the overlap capacitance In addition theprocess allows smaller transistors The result is a signif-icant increase in circuit speed The 74HC-series ofCMOS logic circuits is based on this technology andhas speeds comparable to LS TTL which is to sayabout 10 times faster than the 74C-series circuits

    The size reduction that contributes to the higher speedalso demands an accompanying reduction in the maxi-mum supply voltage High-speed CMOS is generallylimited to 6V

    WHAT IS CHMOS

    CHMOS is the name given to Intels high-speed CMOSprocesses There are two CHMOS processes one basedon an n-well structure and one based on a p-well struc-ture In the n-well structure n-type wells are diffusedinto a p-type substrate Then the n-channel transistors(nFETs) are built into the substrate and pFETs arebuilt into the n-wells In the p-well structure p-typewells are diffused into an n-type substrate Then thenFETs are built into the wells and pFETs into the

    substrate Both processes have their advantages anddisadvantages which are largely transparent to theuser

    Lower operating voltages are easier to obtain with thep-well structure than with the n-well structure But the

    p-well structure does not easily adapt to an EPROMwhich would be pin-for-pin compatible with HMOSEPROMs On the other hand the n-well structure canbe based on the solidly founded HMOS process inwhich nFETs are built into a p-type substrate Thisallows somewhat more than half of the transistors in aCHMOS chip to be constructed by processes that arealready well characterized

    Currently Intels CHMOS microcontrollers and memo-ry products are n-well devices whereas CHMOS mi-croprocessors are p-well devices

    Further discussion of the CHMOS technology is pro-vided in References 1 and 2 (which are reprinted in theMicrocontroller Handbook)

    THE MCS-51 FAMILY IN CHMOS

    The 80C51BH is the CHMOS version of Intels original8051 The 80C31BH is the ROMless 80C51BH equiva-lent to the 8031 These CHMOS devices are architec-turally identical with their HMOS counterparts exceptthat they have two added features for reduced powerThese are the Idle and Power Down modes of opera-tion

    In most cases an 80C51BH can directly replace the8051 in existing applications It can execute the samecode at the same speed accept signals from the samesources and drive the same loads However the80C51BH covers a wider range of speeds will emitCMOS logic levels to CMOS loads and will draw about

    110 the current of an 8051 (and less yet in the reducedpower modes) Interchangeability between the HMOSand CHMOS devices is discussed in more detail in thefinal section of this Application Note

    It should be noted that the 80C51BH CPU is not staticThat means if the clock frequency is too low the CPUmight forget what it was doing This is because thecircuitry uses a number of dynamic nodes A dynamicnode is one that uses the note-to-ground capacitance toform a temporary storage cell Dynamic nodes are usedto reduce the transistor count and hence the chip areathus to produce a more economical device

    This is not to say that the on-chip RAM in CHMOSmicrocontrollers is dynamic Its not Its the CPU thatis dynamic and that is what imposes the minimum

    clock frequency specification

    1

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    6/28

    AP-252

    LATCHUP

    Latchup is an SCR-type turn-on phenomenon that isthe traditional nemesis of CMOS systems The sub-strate the wells and the transistors form parasitic pnpnstructures within the device These parasitic structures

    turn on like an SCR if a sufficient amount of forwardcurrent is driven through one of the junctions Fromthe circuit designers point of view it can happen when-ever an input or output pin is externally driven a diodedrop above VCC or below VSS by a source that is capa-ble of supplying the required trigger current

    However much of a problem latchup has been in thepast it is good to know that in most recently developedCMOS devices and specifically in CHMOS devices thecurrent required to trigger latchup is typically well over100 mA The 80C51BH is virtually immune to latchup(References 1 and 2 present a discussion of the latchupmechanisms and the steps that are taken on the chip toguard against it) Modern CMOS is not absolutely im-mune to latchup but with trigger currents in the hun-dreds of mA latchup is certainly a lot easier to avoid

    than it once was

    A careless power-up sequence might trigger a latchupin the older CMOS families but its unlikely to be amajor problem in high-speed CMOS or in CHMOSThere is still some risk incurred in inserting or remov-ing chips or boards in a CMOS system while the poweris on Also severe transients such as inductive kicks ormomentary short-circuits can exceed the trigger cur-rent for latchup

    For applications in which some latchup risk seems un-avoidable you can put a small resistor (100X or so) inseries with signal lines to ensure that the trigger currentwill never be reached This also helps to control over-shoot and RFI

    LOGIC LEVELS AND INTERFACINGPROBLEMS

    CMOS logic levels differ from TTL levels in two ways

    First for equal supply voltages CMOS gives (and re-quires) a higher logic 1 level than TTL SecondlyCMOS logic levels are VCC (or VDD) dependentwhereas guaranteed TTL logic levels are fixed whenVCC is within TTL specs

    Standard 74HC logic levels are as follows

    VIHMIN e 70% of VCCVILMAX e 20% of VCCVOHMIN e VCC b 01V lIOHl s 20 mAVOLMAX e 01V lIOLl s 20 mA

    Figure 1 compares 74HC LS TTL and 74HCT logiclevels with those of the HMOS 8051 and the CHMOS80C51BH for VCC e 5V

    Output logic levels depend of course on load currentand are normally specified at several load currentsWhen CMOS and TTL are powered by the same VCCthe logic levels guaranteed on the data sheets indicatethat CMOS can drive TTL but TTL cant driveCMOS The incompatibility is that the TTL circuits

    VOH level is too low to reliably be recognized by theCMOS circuit as a valid VIH

    Since HMOS circuits were designed to be TTL-compat-ible they have the same incompatibility

    Fortunately 74HCT-series circuits are available to easethese interfacing problems They have TTL-compatiblelogic levels at the inputs and standard CMOS levels atthe outputs

    The 80C51BH is designed to work with either TTL orCMOS Therefore its logic levels are specified verymuch like 74HCT circuits That is its input logic levelsare TTL-compatible and its output characteristics arelike standard high-speed CMOS

    NOISE CONSIDERATIONS

    One of the major reasons for going to CMOS has tradi-tionally been that CMOS is less susceptible to noise Aspreviously noted its low susceptibility to noise is

    Logic StateVCC e 5V

    74HC 74HCT LS TTL 8051 80C51BH

    VIH 35V 20V 20V 20V 19V

    VIL 10V 08V 08V 08V 09V

    VOH 49V 49V 27V 24V 45V

    VOL 01V 01V 05V 045V 045V

    Figure 1 Logic Level Comparison (Output voltage levels depend on load current

    Data sheets list guaranteed output levels for several load currents The output

    levels listed here are for minimum loading)

    2

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    7/28

    AP-252

    partly due to superior noise margins and partly due toits slow speed

    Noise margin is the difference between VOL and VILor between VOH and VIH If VOH from a driving cir-cuit is 27V and VIH to the driven circuit is 20V then

    the driven circuit has 07V of noise margin at the logichigh level These kinds of comparisons show that anall-CMOS system has wider noise margins than an all-TTL system

    Figure 2 shows noise margins in CMOS and LS TTLsystems when both have VCC e 5V It can be seen thatCMOSCMOS and CMOSCHMOS systems have anedge over LS TTL in this respect

    Noise margins can be misleading however becausethey dont say how much noise energy it takes to inducein the circuit a noise voltage of sufficient amplitude tocause a logic error This would involve consideration ofthe width of the noise pulse as compared with the cir-cuits response speed and the impedance to groundfrom the point of noise introduction in the circuit

    When these considerations are included it is seen thatusing the slower 74C- and 4000-series circuits with a 12or 15V supply voltage does offer a truly improved levelof noise immunity but that high-speed CMOS at 5V isnot significantly better than TTL

    One should not mistake the wider supply voltage toler-ance of high-speed CMOS for VCC glitch immunitySupply voltage tolerance is a DC rating not a glitchrating

    For any clocked CMOS and most especially for VLSICMOS VCC decoupling is critical CHMOS draws

    Noise Margin for

    Interface VCCe

    5VLogic Low Logic High

    VIL VOL VOHVIH

    74HC to 74HC 09V 14V

    LSTTL to LSTTL 03V 07V

    LSTTL to 74HCT 03V 07V

    LSTTL to 80C51BH 03V 07V

    74HC to 80C51BH 08V 30V

    80C51BH to 74HC 08V 10V

    Figure 2 Noise Margins for CMOS

    and LS TTL Circuits

    current in extremely sharp spikes at the clock edgesThe VHF and UHF components of these spikes are notdrawn from the power supply but from the decouplingcapacitor If the decoupling circuit is not sufficientlylow in inductance VCC will glitch at each clock edgeWe suggest that a 01 mF decoupler cap be used in a

    minimum-inductance configuration with the microcon-troller A minimum-inductance configuration is onethat minimizes the area of the loop formed by the chip(VCC to VSS) the traces to the decoupler cap and thedecoupler cap PCB designers too often fail to under-stand that if the traces that connect the decoupler capto the VCC and VSS pins arent short and direct thedecoupler loses much of its effectiveness

    Overshoot and ringing in signal lines are potentialsources of logic upsets These can largely be controlledby circuit layout Inserting small resistors (about 100X)in series with signal lines that seem to need them willalso help

    The sharp edges produced by high-speed CMOS cancause RFI problems The severity of these problems is

    largely a function of the PCB layout We dont mean toimply that all RFI problems can be solved by a betterPCB layout It may well be for example that in someRFI-sensitive designs high-speed CMOS is simply notthe answer But circuit layout is a critical factor in thenoise performance of any electronic system and moreso in high-speed CMOS systems than others

    Circuit layout techniques for minimizing noise suscepti-bility and generation are discussed in References 3through 6

    UNUSED PINS

    CMOS input pins should not be left to float but shouldalways be pulled to one logic level or the other If they

    float they tend to float into the transition region be-tween 0 and 1 where the pullup and pulldown devicesin the input buffer are both conductive This causes asignificant increase in ICC A similar effect exists inHMOS circuits but with less noticeable results

    In 80C51BH and 80C31BH designs unused pins ofPorts 1 2 and 3 can be ignored because they haveinternal pullups that will hold them at a valid Logic 1level Port 0 pins are different however in not havinginternal pullups (except during bus operations)

    When the 80C51BH is in reset the Port 0 pins are in afloat state unless they are externally pulled up or downIf its going to be held in reset for just a short time thetransient float state can probably be ignored When itcomes out of reset the pins stay afloat unless

    3

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    8/28

    AP-252

    they are externally pulled either up or down Alterna-tively the software can internally write 0s to whateverPort 0 pins may be unused

    The same considerations are applicable to the80C31BH with regards to reset But when the

    80C31BH comes out of reset it commences bus opera-tions during which the logic levels at the pins are al-ways well defined as high or low

    Consider the 80C31BH in the Power Down or Idlemodes however In those modes it is not fetching in-structions and the Port 0 pins will float if not external-ly pulled high or low The choice of whether to pullthem high or low is the designers Normally it is suffi-cient to pull them up to VCC with 10k resistors But ifpower is going to be removed from circuits that areconnected to the bus it will be advisable to pull the buspins down (normally with 10k resistors) Considera-tions involved in selecting pullup and pulldown resistorvalues are as follows

    2700681

    Figure 3a Conditions defining the minimum

    value for R P0X is emitting a logic low R must

    be large enough to not cause IOL to exceed

    data sheet specifications

    2700682

    Figure 3b Conditions defining the maximum

    value for R P0X is in a high impedance

    state R must be small enough to keep

    VOH acceptably high

    PULLUP RESISTORS

    If a pullup resistor is to be used on a Port 0 pin itsminimum value is determined by IOL requirements Ifthe pin is trying to emit a 0 then it will have to sink thecurrent from the pullup resistor plus whatever other

    current may be sourced by other loads connected to thepin as shown in Figure 3a while maintaining a validoutput low (VOL) To guarantee that the pin voltagewill not exceed 045V the resistor should be selected sothat IOL doesnt exceed the value specified on the datasheet In most CMOS applications the minimum valuewould be about 2k X

    The maximum value you could use depends on howfast you want the pin to pull up after bus operationshave ceased and how high you want the VOH level tobe The smaller the resistor the faster it pulls up Itseffect on the VOH level is that VOH e VCC b (ILI a

    IIH) c R ILI is the input leakage current to the Port 0pin and IIH is the input high current to the externalloads as shown in Figure 3b Normally VOH can beexpected to reach 09 VCC if the pullup resistance does

    not exceed about 50k X

    Pulldown Resistors

    If a pulldown resistor is to be used on a Port 0 pin itsminimum value is determined by VOH requirementsduring bus operations and its maximum value is inmost cases determined by leakage current

    During bus operations the port uses internal pullups toemit 1s The DC Characteristics in the data sheet listguaranteed VOH levels for given IOH currents (The -sign in the IOH value means the pin is sourcing thatcurrent to the external load as shown in Figure 4) Toensure the VOH level listed in the data sheet the resis-

    2700683

    Figure 4a Conditions defining the minimum

    value for R P0X is emitting a 1 in a bus

    operation R must be large enough to not cause

    IOH to exceed data sheet specifications

    4

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    9/28

    AP-252

    VOH

    Ra IIHs lIOHl

    tor has to satisfy where IIH is the input high current tothe external loads

    When the pin goes into a high impedance state thepulldown resistor will have to sink leakage currentfrom the pin plus whatever other current may besourced by other loads connected to the pin as shownin Figure 4b The Port 0 leakage current is ILI on thedata sheet The resistor should be selected so that thevoltage developed across it by these currents will beseen as a logic low by whatever circuits are connectedto it (including the 80C51BH) In CMOSCHMOS ap-plications 50k X is normally a reasonable maximumvalue

    2700684

    Figure 4b Conditions defining the maximum

    value for R P0X is in a high impedance state

    R must be small enough to keep VOL

    acceptably low

    DRIVE CAPABILITY OF THEINTERNAL PULLUPS

    Theres an important difference between HMOS andCHMOS port drivers The pins of Ports 1 2 and 3 ofthe CHMOS parts each have three pullups strong nor-mal and weak as shown in Figure 5 The strong pullup(p1) is only used during 0-to-1 transitions to hasten thetransition The weak pullup (p2) is on whenever the bitlatch contains a 1 The normal pullup (p3) is con-trolled by the pin voltage itself

    The reason that p3 is controlled by the pin voltage isthat if the pin is being used as an input and the externalsource pulls it to a low then turning off p3 makes for alower IIL The data sheet shows an ITL specificationThis is the current that p3 will source during the timethe pin voltage is making its 1-to-0 transition This iswhat IIL would be if an input low at the pin didnt turnp3 off

    Note however that this p3 turn-off mechanism puts arestriction on the drive capacity of the pin if its being

    used as an output If youre trying to output a logichigh and the external load pulls the pin voltage belowthe pins VIHMIN spec p3 might turn off leaving onlythe weak p2 to provide drive to the load To preventthis happening you need to ensure that the load doesntdraw more than the IOH spec for a valid VOH The ideais to make sure the pin voltage never falls below its ownVIHMIN specification

    2700685

    Figure 5 80C51BH Output Drivers for Ports 1 2 and 3

    5

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    10/28

    AP-252

    POWER CONSUMPTION

    The main reason for going to CMOS of course is toconserve power (There are other reasons but this is themain one) Conserving power doesnt mean just reduc-ing your electric bill Nor does it necessarily relate to

    battery operation although battery operation withoutCMOS is pretty unhandy The main reason for conserv-ing power is to be able to put more functionality into asmaller space The reduced power consumption allowsthe use of smaller and lighter power supplies and lessheat being generated allows denser packaging of circuitcomponents Expensive fans and blowers can usually beeliminated

    A cooler running chip is also more reliable since mostrandom and wearout failures relate to die temperatureAnd finally the lower power dissipation will allowmore functions to be integrated onto the chip

    The reason CMOS consumes less power than NMOS isthat when its in a stable state there is no path of con-duction from VCC to VSS except through various leak-

    age paths CMOS does draw current when its changingstates How much current it draws depends on howoften and how quickly it changes states

    2700686

    Figure 6 80C51BH ICC vs Clock Frequency

    CMOS circuits draw current in sharp spikes during log-ical transitions These current spikes are made up oftwo components One is the current that flows duringthe transition time when pullup and pulldown FETs areboth active The average (DC) value of this componentis larger when the transition times of the input signals

    are longer For this reason if the current draw is acritical factor in the design slow rise and fall timesshould be avoided even when the system speed doesntseem to justify a need for nanosecond switching speeds

    The other component is the current that charges strayand load capacitance at the nodes of a CMOS logicgate The average value of this current spike is its area(integral over time) multiplied by its rep rate Its area isthe amount of charge it takes to raise the node capaci-tance C to VCC That amount of charge is just C xVCC So the average value of the current spike is C xVCC x f where f is the clock frequency

    This component of current increases linearly with clockfrequency For minimal current draw the 80C52BH-2is specd to run at frequencies as low as 500 kHz

    Keep in mind though that other component of currentthat is due to slow rise and fall times A sinusoid is notthe optimal waveform to drive the XTAL1 pin withYet crystal oscillators including the one on the80C51BH generate sinusoidal waveforms Therefore ifthe on-chip oscillator is being used you can expect thedevice to draw more current at 500 kHz than it does at15 MHz as shown in Figure 6 If you derive a goodsharp square wave from an external oscillator and usethat to drive XTAL1 then the microcontroller willdraw less current But the external oscillator will prob-ably make up the difference

    The 80C51BH has two power-saving features not avail-able in the HMOS devices These are the Idle and Pow-er Down modes of operation The on-chip hardware

    that implements these reduced power modes is shownin Figure 7 Both modes are invoked by software

    2700687

    Figure 7 Oscillator and Clock Circuitry Showing Idle and Power Down Hardware

    6

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    11/28

    AP-252

    Idle In the Idle Mode (IDL e 0 in Figure 7) the CPUputs itself to sleep by gating off its own clock It doesntstop the oscillator It just stops the internal clock signalfrom getting to the CPU Since the CPU draws 80 to 90percent of the chips power shutting it off represents afairly significant power savings The on-chip periperals

    (timers serial port interrupts etc) and RAM continueto function as normal The CPU status is preserved inits entirety the Stack Pointer Program Counter Pro-gram Status Word Accumulator and all other regis-ters maintain their data during Idle

    The Idle Mode is invoked by setting bit 0 (IDL) of thePCON register PCON is not bit-addressable so the bithas to be set by a byte operation such as

    ORL PC0N1

    The PCON register also contains flag bits GF0 andGF1 which can be used for any general purposes or togive an indication if an interrupt occurred during nor-mal operation or during Idle In this application theinstruction that invokes Idle also sets one or both of the

    flag bits Their status can then be checked in the inter-rupt routines

    While the device is in the Idle Mode ALE and PSENemit logic high (VOH) as shown in Figure 8 This is soexternal EPROM can be deselected and have its outputdisabled

    The port pins hold the logical states they had at thetime the Idle was activated If the device was executingout of external program memory Port 0 is left in a highimpedance state and Port 2 continues to emit the highbyte of the program counter (using the strong pullupsto emit 1s) If the device was executing out of internalprogram memory Ports 0 and 2 continue to emit what-ever is in the P0 and P2 registers

    There are two ways to terminate Idle Activation of anyenabled interrupt will cause the hardware to clear bit 0of the PCON register terminating the Idle mode Theinterrupt will be serviced and following RETI the nextinstruction to be executed will be the one following theinstruction that invoked Idle

    The other way is with a hardware reset Since the clockoscillator is still running RST only needs to be heldactive for two machine cycles (24 oscillator periods) tocomplete the reset Note that this exit from Idle writes1s to all the ports initializes all SFRs to their resetvalues and restarts program execution from location 0

    Power Down In the Power Down Mode (PD e 0 inFigure 7) the CPU puts the whole chip to sleep byturning off the oscillator In case it was running froman external oscillator it also gates off the path to theinternal phase generators so no internal clock is gener-ated even if the external oscillator is still running Theon-chip RAM however saves its data as long as VCCis maintained In this mode the only ICC that flows isleakage which is normally in the micro-amp range

    The Power Down Mode is invoked by setting bit 1 inthe PCON register using a byte instruction such as

    ORL PCON2

    While the device is in Power Down ALE and PSENemit lows (VOL) as shown in Figure 8 The reason theyare designed to emit lows is so that power can be re-moved from the rest of the circuit if desired while the80CS51BH is in its Power Down mode

    The port pins continue to emit whatever data was writ-ten to them Note that Port 2 emits its P2 register dataeven if execution was from external program memory

    PinInternal Execution External Execution

    Idle Power Down Idle Power Down

    ALE 1 0 1 0

    PSEN 1 0 1 0

    P0 SFR Data SFR Data High-Z High-Z

    P1 SFR Data SFR Data SFR Data SFR Data

    P2 SFR Data SFR Data PCH SFR Data

    P3 SFR Data SFR Data SFR Data SFR Data

    Figure 8 Status of Pins in Idle and Power Down Modes SFR data means the port pins emit their

    internal register data PCH is the high byte of the Program Counter

    7

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    12/28

    AP-252

    Port 0 also emits its P0 register data but if executionwas from external program memory the P0 registerdata is FF The oscillator is stopped and the part re-mains in this state as long as VCC is held and until itreceives an external reset signal

    The only exit from Power Down is a hardware resetSince the oscillator was stopped RST must be held ac-tive long enough for the oscillator to re-start and stabi-lize Then the reset function initializes all the SpecialFunction Registers (ports timers etc) to their resetvalues and re-starts the program from location 0Therefore timer reloads interrupt enables baud ratesport status etc need to be re-established Reset doesnot affect the content of the on-chip data RAM If V CCwas held during Power Down the RAM data is stillgood

    USING THE POWER DOWN MODE

    The software-invoked Power Down feature offers ameans of reducing the power consumption to a mere

    trickle in systems which are to remain dormant forsome period of time while retaining important data

    The user should give some thought to what state theport pins should be left in during the time the clock isstopped and write those values to the port latches be-fore invoking Power Down

    If VCC is going to be held to the entire circuit onewould want to write values to the port latches thatwould deselect peripherals before invoking PowerDown For example if external memory is being usedthe P2 SFR should be loaded with a value which willnot generate an active chip select to any memory de-

    vice

    In some applications VCC to part of the system may beshut off during Power Down so that even quiescentand standby currents are eliminated Signal lines thatconnect to those chips must be brought to a logic lowwhether the chip in question is CMOS NMOS orTTL before VCC is shut off to them CMOS pins haveparasitic pn junctions to VCC which will be forwardbiased if VCC is reduced to zero while the pin is held ata logic high NMOS pins often have FETs that looklike diodes to VCC TTL circuits may actually be dam-aged by an input high if VCC e 0 Thats why the80C51BH outputs lows at ALE and PSEN during Pow-er Down

    Figure 9 shows a circuit that can be used to turn VCC

    off to part of the system during Power Down The cir-cuit will ensure that the secondary circuit is not de-en-ergized until after the 80C31BH is in Power Down andthat the 80C31BH does not receive a reset (terminatingthe Power Down mode) before the secondary circuit isre-energized Therefore the program memory itself canbe part of the secondary circuit

    2700688

    Figure 9 The 80C31BH de-energizes part of the circuit (VCC2) when it goes into Power Down

    Selections of R and Q2 depend on VCC2 current draw

    8

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    13/28

    AP-252

    In Figure 9 when VCC is switched on to the 80C31BHcapacitor C1 provides a power-on reset The reset func-tion writes 1s to all the port pins The 1 at P26 turnsQ1 on enabling VCC to the secondary circuit throughtransistor Q2 As the 80C31BH comes out of reset Port2 commences emitting the high byte of the Program

    Counter which results in the P27 and P26 pins out-putting 0s The 0 at P27 ensures continuation of V CCto the secondary circuit

    The system software must now write a 1 to P27 and a 0to P26 in the Port 2 SFR P2 These values will notappear at the Port 2 pins as long as the device is fetch-ing instructions from external program memory How-ever whenever the 80C31BH goes into Power Downthese values will appear at the port pins and will shutoff both transistors disabling VCC to the secondary cir-cuit

    Closing the switch S1 re-energizes the secondary cir-cuit and at the same time sends a reset through C2 tothe 80C31BH to wake it up The diode D1 is to preventC1 from hogging current from C2 during this second-

    ary reset D2 prevents C2 from discharging through theRST pin when VCC to the secondary circuit goes tozero

    2700689

    a Using a pFET

    27006828

    b Using an nFET

    Figure 10 Using Power MOSFETs

    to Control VCC2

    USING POWER MOSFETs toCONTROL VCC

    Power MOSFETs are gaining in popularity (and avail-ability) The easiest way to control VCC is with a LogicLevel pFET as shown in Figure 10a This circuit al-lows the full VCC to be used to turn the device onUnfortunately power pFETs are not economicallycompetitive with bipolar transistors of comparable rat-ings

    Power nFETs are both economical and available andcan be used in this application if a DC supply of highervoltage is available to drive the gate Figure 10b showshow to implement a VCC switch using a power nFETand a (nominally) a 12V supply The problem here isthat if the device is on its source voltage is a5V Tomaintain the on state the gate has to be another 5 or10V above that The 12V supply is not particularlycritical A minimally filtered unregulated rectifier willsuffice

    BATTERY BACKUP SYSTEMS

    Here we consider circuits that normally draw powerfrom the AC line but switch to battery operation in theevent of a power failure We assume that in batteryoperation high-current loads will be allowed to diealong with the AC power The system may continuethen with reduced functionality monitoring a controltransducer perhaps or driving an LCD Or it may gointo a bare-bones survival mode in which critical datais saved but nothing else happens till AC power is re-stored

    In any case it is necessary to have some early warningof an impending power failure so that the system canarrange an orderly transfer to battery power Earlywarning systems can operate by monitoring either the

    AC line voltage or the unregulated rectifier output oreven by monitoring the regulated DC voltage

    Monitoring the AC line voltage gives the earliest warn-ing That way you can know within one or two half-cy-cles of line frequency that AC power is down In mostcases you then have at least another half-cycle of linefrequency before the regulated VCC starts to fall In ahalf-cycle of line frequency an 80C51BH can executeabout 5000 instructionsplenty of time to arrange anorderly transfer of power

    The circuit in Figure 11 uses a Zener diode to test theline voltage each half-cycle and a junction transistor topass the information on to the 80C51BH (Obviously avoltage comparator with a suitable reference source can

    9

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    14/28

    AP-252

    27006810

    Figure 11 Power Failure Detector with Battery Backup When AC power fails

    VCC1 goes down and VCC2 is held

    perform the same function if one prefers) The way itworks is if the line voltage reaches an acceptably highlevel it breaks over Z1 drives Q1 to saturation andinterrupts the 80C51BH The interrupt would be tran-sition-activated in this application The interrupt serv-ice routine reloads one of the C51BHs timers to a valuethat will make it roll over in something between oneand two half-cycles of line frequency As long as theline voltage is healthy the timer never rolls over be-cause it is reloaded every half-cycle If there is a singlehalf-cycle in which the line voltage doesnt reach a highenough level to generate the interrupt the timer rollsover and generates a timer interrupt

    The timer interrupt then commences the transition tobattery backup Critical data needs to be copied intoprotected RAM Signals to circuits that are going tolose power must be written to logic low Protected cir-cuits (those powered by VCC2) that communicate withunprotected circuits must be deselected The microcon-troller itself may be put into Idle so that it can contin-ue some level of interrupt-driven functionality or itmay be put into Power Down

    Note that if the CPU is going to invoke Power Downthe Special Function Registers may also need to be cop-ied into protected RAM since the reset that terminatesthe Power Down mode will also intialize all the SFRsto their reset values

    The circuit in Figure 11 does not show a wake-upmechanism A number of choices are available howev-er A pushbutton could be used to generate an inter-rupt if the CPU is in Idle or to activate reset if theCPU is in Power Down

    Automatic wake-up on power restoration is also possi-ble If the CPU is in Idle it can continue to respond toany interrupts that might be generated by Q1 The in-terrupt service routine determines from the status offlag bits GF0 and GF1 in PCON that it is in Idle be-cause there was a power outage It can then sampleVCC1 through a voltage comparator similar to Z1 Q1in Figure 11 A satisfactory level of VCC1 would beindicated by the transistor being in saturation

    But perhaps you cant spare the timer that is the key tothe operation of the circuit in Figure 11 In that case aretriggerable one-shot triggered by the AC line voltagecan perform essentially the same function Figure 12shows an example of this type of power failure detectorA retriggerable one-shot (one half of a 74HC123) moni-tors the AC line voltage through transistor Q1 Q1 re-triggers the one-shot every half-cycle of line frequencyIf the output pulse width is between one and two half-cycles of line frequency then a single missing or lowhalf-cycle will generate an active low warning flagwhich can be used to interrupt the microcontroller

    The interrupt routine takes care of the transition tobattery backup From this point VCC1 may or may notactually drop out The missing half-cycle of line voltagethat caused the power down sequence may have beennothing more than a short glitch If the AC line comesback strong enough to trigger the one-shot while VCC1is still up (as indicated by the state of transistor Q2)then the other half of the 74HC123 will generate awake-up signal

    10

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    15/28

    AP-252

    27006811

    Figure 12 Power Failure Detector uses retriggerable one-shots to flag impending power outage and

    generate automatic wake-up when power returns

    Having been awakened the 80C51BH will stay awakefor at least another half-cycle of line frequency (another5000 or so instructions) before possibly being told toarrange another transfer of power Consequently if theline voltage is jittering erratically around the switch-over point (determined by diode Z1) the system willlimp along executing in half-cycle units of line frequen-cy

    On the other hand if the power outage is real andlengthy VCC1 will eventually fall below the level atwhich the backup battery takes over The backup bat-tery maintains power to the 80C51BH and to the74HC123 and to whatever other circuits are being pro-tected during this outage The battery voltage must be

    high enough to maintain VCCMIN specs to the80C51BH

    If the microcontroller is an 80C31BH executing out ofexternal ROM and if the C31BH is put into Idle dur-ing the power outage then the external ROM must alsobe supplied by the battery On the other hand if theC31BH is put into Power Down during the outagethen the ROM can be allowed to die with the AC pow-er The considerations here are the same as in Figure 9VCC to the ROM is still up at the time Power Down isinvoked and we must ensure (through selection of di-ode Z2 in Figure 12) that the 80C31BH is not awak-ened till ROM power is back in spec

    POWER SWITCHOVER CIRCUITS

    Battery backup systems need to have a way for theprotected circuits to draw power from the line-operatedpower supply when that source is available and toswitch over to battery power when required Theswitchover circuit is simple if the entire system is to bebattery powered in the event of a line power outage Inthat case a pair of diodes suffice as shown in Figure 12provided VCCMIN specs are still met after the diodedrop has been subtracted from its respective powersource

    The situation becomes more complicated when part ofthe circuit is going to be allowed to die when the AC

    power goes out In that case it is difficult to maintainequal VCCs to protected and unprotected circuits (andpossibly dangerous not to)

    The problem can be alleviated by using a Schottky di-ode instead of a 1N4001 for its lower forward voltagedrop The 1N5820 for example has a foward drop ofabout 035V at 1A

    Other solutions are to use a transistor or power MOS-FET switch as shown in Figure 13 With minor modifi-cations this switch can be controlled by port pins

    11

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    16/28

    AP-252

    27006827

    a Using a pnp Transistor

    27006812

    b Using a Power MOSFET

    Figure 13 Power Switchover Ckts

    80C31BH a CHMOS EPROM

    The 27C64 and 87C64 are Intels 8K byte CHMOSEPROMs The 27C64 requires an external addresslatch and can be used with the 80C31BH as shown inFigure 14a In most 8031 a 2764 (HMOS) appli-

    cations the 2764s Chip Enable (CE) pin is hardwiredto ground (since its normally the only program memo-ry on the bus) This can be done with the CHMOSversions as well but there is some advantage in con-necting CE to ALE as shown in Figure 14a The ad-vantage is that if the 80C31BH is put into Idle mode

    since ALE goes to a 1 in that mode the 27C64 will bedeselected and go into a low current standby mode

    The timing waveforms for this configuration are shownin Figure 14b In Figure 14b the signals and timingparameters in parenthesis are those of the 27C64 andthe others are of the 80C31BH except Tprop is a pa-rameter of the address latch The requirements for tim-ing compatibility are

    TAVIV b Tprop l tACC

    TLLIV l tCE

    TPLIV l tOE

    TPXIZ l tDF

    If the application is going to use the Power Down modethen we have another consideration In Idle ALE e

    PSEN e 1 and in Power Down ALE e PSEN e 0In a realistic application there are likely to be morechips in the circuit than are shown in Figure 14 and itis likely that the nonessential ones will have their VCCremoved while the CPU is in Power Down In that casethe EPROM and the address latch should be amongthe chips that have VCC removed and logic lows areexactly what are required at ALE and PSEN

    But if VCC is going to be maintained to the EPROMduring Power Down then it will be necessary to de-

    27006826

    Figure 14a 80C31BH a 27C64

    12

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    17/28

    AP-252

    27006813

    Figure 14b Timing Waveforms for 80C31BH a

    27C64

    select the EPROM when the CPU is in Power Down IfIdle is never invoked CE of the EPROM can be con-

    nected to P27 of the 80C31BH as shown in Figure15a In normal operation P27 will be emitting theMSB of the Program Counter which is 0 if the pro-gram contains less than 32K of code Then when theCPU goes into Power Down the Port 2 pins emit P2SFR data which puts a 1 at P27 thus deselecting theEPROM

    If Idle and Power Down are both going to be used CEof the EPROM can be driven by the logical OR of ALEand P27 as shown in Figure 15b In Idle ALE e 1will deselect the EPROM and in Power Down P27 e

    1 will deselect it

    27006814

    a Power Down is used but not idle

    27006815

    b Idle and Power Down both used

    Figure 15 Modifications to 80C31BH27C64

    Interface

    Pulldown resistors are shown in Figure 14a under theassumption that something on the bus is going to haveits VCC removed during Power Down If this is not thecase pullups can be used as well as pulldowns

    The 87C64 is like the 27C64 except that it has an on-chip address latch The Port 0 pins are tied to bothaddress and data pins of the 87C64 as shown in Figure16a ALE drives the EPROMs ALECS input DuringALE high the address information is allowed to flowinto the EPROM and begin accessing the code byte On

    the falling edge of ALE the address byte is internallylatched The A0A7 inputs are then ignored and thesame bus lines are used to transmit the fetched codebyte from the O0O7 pins back to the 80C31BH

    The timing waveforms for this configuration are shownin Figure 16b In Figure 16b the signals and timingparameters in parentheses are those of the 87C64 andthe others are of the 80C31BH The requirements fortiming compatibility are

    TLHLL l tLL

    TAVLL l tAL

    TLLAX l tLA

    TLLIV l tACL

    TPLIV l tOE

    TLLPL l tCOE

    TPXIZ l tOHZ

    The same considerations apply to the 87C64 as to the27C64 with regards to the Idle and Power Downmodes Basically you want CS e 1 if VCC is main-tained to the EPROM and CS e OE e 0 if VCC isremoved

    SCANNING A KEYBOARD

    There are many different kinds of keyboards but alpha-numeric keyboards generally consist of a matrix of 8scan lines and 8 receive lines as shown in Figure 17Each set of lines connects to one port of the microcon-troller The software has written 0s to the scan linesand 1s to the receive lines Pressing a key connects ascan line to a receive line thus pulling the receive lineto a logic low

    The 8 receive lines are ANDed to one of the externalinterrupt pins so that pulling any of the receive lineslow generates an interrupt The interrupt service rou-tine has to identify the pressed key if only one key isdown and convert that information to some useful out-put If more than one key in the line matrix is found tobe pressed no action is taken (This is a two key lock-out scheme)

    13

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    18/28

    AP-252

    On some keyboards certain keys (Shift Control Es-cape etc) are not a part of the line matrix These keyswould connect directly to a port pin on the microcon-troller and would not cause lock-out if pressed simulta-neously with a matrix key nor generate an interrupt ifpressed singly

    Normally the microcontroller would be in idle modewhen a key has not been pressed and another task isnot in progress Pressing a matrix key generates an in-

    terrupt which terminates the Idle The interrupt serv-ice routine would first call a 30 ms (or so) delay todebounce the key and then set about the task of identi-fying which key is down

    First the current state of the receive lines is latched

    into an internal register If a single key is down all butone of the lines would be read as 1s Then 0s are writtento the receive lines and 1s to the scan lines and the scanlines are read If a single key is down all but one of

    27006816

    Figure 16a 80C31BH a 87C64

    27006817

    Figure 16b Timing Waveforms for 80C31BH a 87C64

    14

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    19/28

    AP-252

    these lines would be read as 1s By locating the single 0in each set of lines the pressed key can be identified Ifmore than one matrix key is down one or both sets oflines will contain multiple 0s

    A subroutine is used to determine which of 8 bits in

    either set of lines is 0 and whether more than one bit is0 Figure 18 shows a subroutine (SCAN) which doesthat using the 8051s bit-addressing capability To usethe subroutine move the line data into a bit-address-able RAM location named LINE and call the SCANroutine The number of LINE bits which are zero isreturned in ZEROCOUNTER If only one bit iszero its number (1 through 8) is returned in ZEROBIT

    The interrupt service routine that is executed in re-sponse to a key closure might then be as follows

    RESPONSE TO KEY CLOSURECALL DEBOUNCE DELAYMOV LINEP1 See Figure 17CALL SCANDJNZ ZERO COUNTERREJECTMOV ADDRESSZERO BIT

    MOV P20FFH See Figure 17MOV P10MOV LINEP2CALL SCANDJNZ ZERO COUNTERREJECTXCH AZ ERO BITSWAP AORL ADDRESSAXCH AZ ERO BITMOV P10FFHMOV P2O

    REJECT CLR EX0RETI

    27006818

    Figure 17 Scanning a Keyboard

    15

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    20/28

    AP-252

    27006819

    Figure 18 Subroutine SCAN Determines Which of 8 Bits in LINE is Zero

    Notice that RESPONSE

    TO

    KEY

    CLOSUREdoes not change the Accumulator the PSW nor any ofthe registers R0 through R7 Neither do SCAN or DE-BOUNCEDELAY

    What we come out with then is a one-byte key address(ADDRESS) which identifies the pressed key Thekeys scan line number is in the upper nibble of AD-DRESS and its receive line number is in the lowernibble ADDRESS can be used in a look-up table togenerate a key code to transmit to a host computerandor to a display device

    The keyboard interrupt itself must be edge-triggeredrather than level-activated so that the interrupt routineis invoked when a key is pressed and is not constantlybeing repeated as long as the key is held down In edge-triggered mode the on-chip hardware clears the inter-rupt flag (EX0 in this case) as the service routine isbeing vectored to In this application however contactbounce will cause several more edges to occur after theservice routine has been vectored to during the DE-BOUNCEDELAY routine Consequently it is neces-sary to clear EX0 again in software before executingRETI

    The debounce delay routine also takes advantage of theIdle mode In this routine a timer must be preloadedwith a value appropriate to the desired length of delayThis would be

    timer preload e(osc kHz) c (delay time ms)

    12

    For example with a 358 MHz oscillator frequency a30 ms delay could be obtained using a preload value ofb8950 or DD0A in hex digits

    In the debounce delay routine (Figure 19) the timerinterrupt is enabled and set to a higher priority than thekeyboard interrupt because as we invoke Idle the key-board interrupt is still in progress An interrupt ofthe same priority will not be acknowledged and willnot terminate the Idle mode With the timer interruptset to priority 1 while the keyboard interrupt is a prior-ity 0 the timer interrupt when it occurs will be ac-knowledged and will wake up the CPU The timer in-terrupt service routine does not itself have to do any-thing The service routine might be nothing more thana single RETI instruction RETI from the timer inter-rupt service routine then returns execution to the de-bounce delay routine which shuts down the timer andreturns execution to the keyboard service routine

    DRIVING AN LCD

    An LCD (Liquid Crystal Display) consists of a back-plane and any number of segments or dots which willbe used to form the image being displayed Applying avoltage (nominally 4 or 5V) between any segment andthe backplane causes the segment to darken The onlycatch is that the polarity of the applied voltage has tobe periodically reversed or else a chemical reac-

    16

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    21/28

    AP-252

    27006820

    Figure 19 Subroutine DEBOUNCEDELAY Puts the 80C51BH into Idle During the Delay Time

    tion takes place in the LCD which causes deteriorationand eventual failure of the liquid crystal

    To prevent this happening the backplane and all thesegments are driven with an AC signal which is de-rived from a rectangular voltage waveform If a seg-ment is to be off it is driven by the same waveform asthe backplane Thus it is always at backplane potentialIf the segment is to be on it is driven with a wave-

    form that is the inverse of the backplane waveformThus it has about 5V of periodically changing polaritybetween it and the backplane

    With a little software overhead the 80C51BH can per-form this task without the need for additional LCDdrivers The only drawback is that each LCD segmentuses up one port pin and the backplane uses one moreIf more than say two 7-segment digits are being driv-en there arent many port pins left for other tasksNevertheless assuming a given application leavesenough port pins available to support this task the con-siderations for driving the LCD are as follows

    Suppose for example it is a 2-digit display with a deci-mal point One port (TENSDIGIT) connects to the 7segments of the tens digit plus the backplane Another

    port (ONESDIGIT) connects to a decimal point plusthe 7 segments of the ones digit

    One of the 80C51BHs timers is used to mark off half-periods of the drive voltage waveform The LCD drivewaveform should have a rep rate between 30 and 100Hz but its not very critical A half-period of 12 ms willset the rep rate to about 42 Hz The preloadreloadvalue to get 12 ms to rollover is the 2s complementnegative of the oscillator frequency in kHz if the oscil-lator frequency is 358 MHz the reload value isb3580 or F204 in hex digits

    Now the 80C51BH would normally be in Idle to con-serve power during the time that the LCD and other

    tasks are not requiring servicing When the timer rollsover it generates an interrupt which brings the80C51BH out of Idle The service routine reloads thetimer (for the next rollover) and inverts the logic levelsof all the pins that are connected to the LCD It mightlook like this

    LCD DRIVE INTERRUPTMOV TL1LOW( 1 XTAL FREQ)

    MOV TH1HIGH( 1 XTAL FREQ)XRL TENS DIGIT0FFHXRL ONES DIGIT0FFHRETI

    To update the display one would use a look-up table togenerate the characters In the table on segments arerepresented as 1s and off segments as 0s The back-plane bit is represented as a 0 The quantity to be dis-played is stored in RAM as a BCD value The look-uptable operates on the low nibble of the BCD value andproduces the bit pattern that is to be written to eitherthe ones digit or the tens digit Before the new patternscan be written to the LCD the LCD drive interrupt hasto be disabled That is to prevent a polarity reversalfrom taking place between the times the two digits arewritten An update subroutine is shown in Figure 20

    USING AN LCD DRIVER

    As was noted driving an LCD directly with an80C51BH uses a lot of port pins LCD drivers are avail-able in CMOS to interface an 80C51BH to a 4-digitdisplay using only 7 of the C51BHs IO pins Basical-ly the C51BH tells the LCD driver what digit is to bedisplayed (4 bits) and what position it is to be displayedin (2 bits) and toggles a Chip Select pin to tell thedriver to latch this information The LCD driver gener-ates the display characters (hex digits) and takes careof the polarity reversals using its own RC oscillator togenerate the timing

    17

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    22/28

    AP-252

    Figure 21a shows an 80C51BH working with anICM7211M to drive a 4-digit LCD and the softwarethat updates the display

    One could equally well send information to the LCDdriver over the bus In that case one would set up the

    Accumulator with the digit select and data input bitsand execute a MOVX R0A instruction The LCDdrivers chip select would be driven by the CPUs WRsignal This is a little easier in software than the directbit manipulation shown in Figure 21a However it usesmore IO pins unless there is already some externalmemory involved In that case no extra pins are usedup by adding the LCD driver to the bus

    RESONANT TRANSDUCERS

    Analog transducers are often used to convert the valueof a physical property such as temperature pressureetc to an analog voltage These kinds of transducersthen require an analog-to-digital converter to put themeasurement into a form that is compatible with a digi-

    tal control system Another kind of transducer is nowbecoming available that encodes the value of the physi-cal property into a signal that can be directly read by adigital control system These devices are called reso-nant transducers

    Resonant transducers are oscillators whose frequencydepends in a known way on the physical property beingmeasured These devices output a train of rectangularpulses whose repetition rate encodes the value of thequantity being measured The pulses can in most casesbe fed directly into the 80C51BH which then measureseither the frequency or period of the incoming signalbasing the measurement on the accuracy of its ownclock oscillator The 80C51BH can even do this in itssleep that is in Idle

    When the frequency or period measurement is complet-ed the C51BH wakes itself up for a very short time toperform a sanity check on the measurement and con-vert it in software to any scaling of the measured quan-tity that may be desired The software conversion caninclude corrections for nonlinearities in the transduc-

    ers transfer function

    Resolution is also controlled by software and can evenbe dynamically varied to meet changing needs as a situ-ation becomes more critical For example in a processcontroller you can increase your resolution (fine tunethe control as it were) as the process approaches itstarget

    The nominal reference frequency of the output signalfrom these devices is in the range of 20 Hz to 500 kHzdepending on the design Transducers are available thathave a full scale frequency shift 2 to 1 The transduceroperates from a supply voltage range of 3V to 20Vwhich means it can operate from the same supply volt-age as the 80C51BH At 5V the transducer draws lessthan 5 mA (Reference 7) It can normally be connected

    directly to one of the C51BHs port pins as shown inFigure 22

    FREQUENCY MEASUREMENTS

    Measuring a frequency means counting pulses for aknown sample time Two timercounters can be usedone to mark off the sample time and one to count puls-es If the frequency being counted doesnt exceed 50kHz or so one may equally well connect the transducersignal to one of the external interrupt pins and countpulses in software That frees up one timer with verylittle cost in CPU time

    The count that is directly obtained is TxF where T isthe sample time and F is the frequency The full scale

    27006821

    Figure 20 UPDATELCD Routine Writes Two Digits to an LCD

    18

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    23/28

    AP-252

    range is Tx(Fmax-Fmin) For n-bit resolution

    1 LSB eTx(Fmax-Fmin)

    2n

    Therefore the sample time required for n-bit resolution

    is

    T e2n

    Fmax-Fmin

    For example 8-bit resolution in the measurement of afrequency that varies between 7 kHz and 9 kHz wouldrequire according to this formula a sample time of 128ms The maximum acceptable frequency count wouldbe 128 ms c 9 kHz e 1152 counts The minimumwould be 896 counts Subtracting 896 from each fre-

    quency count (or presetting the frequency counter tob896 e 0FC80H) would allow the frequency to bereported on a scale of 0 to FF in hex digits

    27006822

    Figure 21a Using an LCD Driver

    27006823

    Figure 21b UPDATELCD Routine Writes 4 Digits to an LCD Driver

    19

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    24/28

    AP-252

    27006824

    Figure 22 Resonant Transducer Does Not

    Require an AD Converter

    To implement the measurement one timer is used toestablish the sample time The timer is preset to a valuethat causes it to roll over at the end of the sample timegenerating an interrupt and waking the CPU from its

    Idle mode The required preset value is the 2s comple-ment negative of the sample time measured in machinecycles The conversion from sample time to machinecycles is to multiply it by 112 the clock frequency Forexample if the clock frequency is 12 MHz then a sam-ple time of 128 ms is

    (128 ms) c (12000 kHz)12 e 128000 machine cycles

    Then the required preset value to cause the timer to rollover in 128 ms is

    b128000 e FE0C00 in hex digits

    Note that the preset value is 3 bytes wide whereas thetimer is only 2 bytes wide This means the timer mustbe augmented in software in the timer interrupt routine

    to three bytes The 80C51BH has a DJNZ instruction(decrement and jump if not zero) that makes it easier tocode the third timer byte to count down instead of upIf the third timer byte counts down its reload value isthe 2s complement of what it would be for an up-coun-ter For example if the 2s complement of the sampletime is FE0C00 then the reload value for the thirdtimer byte would be 02 instead of FE The timer inter-rupt routine might then be

    TIMER INTERRUPT ROUTINEDNJZ THIRD TIMER BYTEOUTMOV TL00MOV TH00CHMOV THIRD TIMERBYTE2MOV FREQUENCYCOUNTER LO

    Preset COUNTER to 1896MOV COUNTER LO80HMOV COUNTER HI0FCH

    OUT RETI

    At this point the value of the frequency of the transduc-er signal measured to 8 bit resolution is contained inFREQUENCY Note that the timer can be reloaded onthe fly Note too that the timer can be reloaded on thefly Note too that for 8-bit resolution only the low byteof the frequency counter needs to be read since the

    high byte is necessarily 0 However one may want totest the high byte to ensure that it is zero as a sanitycheck on the data Both bytes of course must be re-loaded

    PERIOD MEASUREMENTS

    Measuring the period of the transducer signal meansmeasuring the total elapsed time over a known numberN of transducer pulses The quantity that is directlymeasured is NT where T is the period of the transduc-er signal in machine cycles The relationship between Tin machine cycles and the transducer frequency F inarbitrary frequency units is

    T eFxtal

    F

    c (112)

    where Fxtal is the 80C51BH clock frequency in thesame units as F

    The full scale range then is Nx (TmaxbTmin) Forn-bit resolution

    1 LSB eNs(Tmax-Tmin)

    2n

    Therefore the number of periods over which the elapsedtime should be measured is

    N e2n

    Tmax-Tmin

    However N must also be an integer It is logical toevaluate the above formula (dont forget Tmax andTmin have to be in machine cycles) and select for N thenext higher integer This selection gives a period mea-surement that has somewhat more than n-bit resolu-tion but it can be scaled back if desired

    For example suppose we want 8-bit resolution in themeasurement of the period of a signal whose frequencyvaries from 71 kHz to 9 kHz If the clock frequency is12 MHz then Tmax is (12000 kHz71 kHz) x (112)e 141 machine cycles Tmin is 111 machine cyclesThe required value for N then is 256(141-111) e

    853 periods according to the formula Using N e 9periods will give a maximum NT value of 141 x 9 e

    1269 machine cycles The minimum NT will be 111 c

    9 e 999 machine cycles A lookup table can be used to

    20

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    25/28

    AP-252

    scale these values back to a range of 0 to 255 givingprecisely the 8-bit resolution desired

    To implement the measurement one timer is used tomeasure the elapsed time NT The transducer is con-nected to one of the external interrupt pins and this

    interrupt is configured to the transition-activated modeIn the transition-activated mode every 1-to-0 transitionin the transducer output will generate an interrupt Theinterrupt routine counts transducer pulses and when itgets to the predetermined N it reads and clears thetimer For the specific example cited above the inter-rupt routine might be

    INTERRUPT RESPONSEDJNZ NOUTMOV N9CLR EACLR TR1MOV NT LOTL1MOV NT HITH1MOV TL19MOV TH10

    SETB TR1SETB EACALL L OOKU P TA BLE

    OUT RETI

    In this routine a pulse counter N is decremented fromits preset value 9 to zero When the counter gets tozero it is reloaded to 9 Then all interrupts are blockedfor a short time while the timer is read and cleared Thetimer is stopped during the read and clear operationsso clearing it actually means presetting it to 9 tomake up for the 9 machine cycles that are missed whilethe timer is stopped

    The subroutine LOOKUPTABLE is used to scalethe measurement back to the desired 8-bit resolution Itcan also include built-in corrections for errors or non-

    linearities in the transducers transfer function

    The subroutine uses the MOVC A A a DPTRinstruction to access the table which contains 270 en-tries commencing at the 16-bit address referred to asTABLE The subroutine must compute the address ofthe table entry that corresponds to the measured valueof NT This address is

    DPTR e TABL a NT b NTMIN

    where NTMIN e 999 in this specific example

    LOOKUP TABLEPUSH ACCPUSH PSWMOV ALOW(TABLE-NTMIN)

    ADD ANT LOMO V D PLAMOV AHIGH(TABLE-NMTIN)

    ADDC ANT HIMOV DP HACLR AMOVC AA0DTPRMOV PERIODAPOP PSW

    POP ACCRET

    At this point the value of the period of the transducersignal measured to 8 bit resolution is contained in PE-RIOD

    PULSE WIDTH MEASUREMENTS

    The 80C51BH timers have an operating mode which isparticularly suited to pulse width measurements andwill be useful in these applications if the transducersignal has a fixed duty cycle

    In this mode the timer is turned on by the on-chipcircuitry in response to an input high at the external

    interrupt pin and off by an input low and it can do thiswhile the 80C51BH is in Idle (The GATE mode oftimer operation is described in the Intel Microcontrol-ler Handbook) The external interrupt itself can be en-abled so the same 1-to-0 transition from the transducerthat turns off the timer also generates an interrupt Theinterrupt routine then reads and resets the timer

    The advantage of this method is that the transducersignal has direct access to the timer gate with the resultthat variations in interrupt response time have no effecton the measurement

    Resonant transducers that are designed to fully exploitthe GATE mode have an internal divide-by-N circuitthat fixes the duty cycle at 50% and lowers the outputfrequency to the range of 250 to 500 Hz (to control

    RFI) The transfer function between transducer periodand measurand is approximately linear with knownand repeatable error functions

    HMOSCHMOS Interchangeability

    The CHMOS version of the 8051 is architecturallyidentical with the HMOS version but there are never-theless some important differences between them whichthe designer should be aware of In addition some ap-plications require interchangeability between HMOSand CHMOS parts The differences that need to be con-sidered are as follows

    External Clock Drive To drive the HMOS 8051 withan external clock signal one normally grounds the

    XTAL1 pin and drives the XTAL2 pin To drive theCHMOS 8051 with an external clock signal one mustdrive the XTAL1 pin and leave the XTAL2 pin uncon-nected The reason for the difference is that in the

    21

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    26/28

    AP-252

    HMOS 8051 it is the XTAL2 pin that drives the inter-nal clocking circuits whereas in the CHMOS version itis the XTAL1 pin that drives the internal clocking cir-cuits

    There are several ways to design an external clock drive

    to work with both types For low clock frequencies (be-low 6 MHz) the HMOS 8051 can be driven in the sameway as the CHMOS version namely through XTAL1with XTAL2 unconnected Another way is to driveboth XTAL1 and XTAL2 that is drive XTAL1 anduse and external inverter to derive from XTAL1 a sig-nal with which to drive XTAL2

    In either case a 74HC or 74HCT circuit makes an ex-cellent driver for XTAL1 andor XTAL2 because nei-ther the HMOS nor the CHMOS XTAL pins haveTTL-like input logic levels

    Unused Pins Unused pins of Ports 1 2 and 3 can beignored in both HMOS and CHMOS designs The in-ternal pullups will put them into a defined state Un-used Port 0 pins in 8051 applications can be ignored

    even if theyre floating But in 80C51BH applicationsthese pins should not be left afloat They can be exter-nally pulled up or down or they can be internallypulled down by writing 0s to them

    803180C31BH designs may or may not need pullupson Port 0 Pullups arent needed for program fetchesbecause in bus operations the pins are actively pulledhigh or low by either the 8031 or the external programmemory But they are needed for the CHMOS part ifthe Idle or Power Down mode is invoked because inthese modes Port 0 floats

    Logic Levels If VCC is between 45V and 55V aninput signal that meets the HMOS 8051s input logiclevels will also meet the CHMOS 80C51BHs input log-ic levels (except for XTAL1XTAL2 and RST) For

    the same VCC condition the CHMOS device will reachor surpass the output logic levels of the HMOS deviceThe HMOS device will not necessarily reach the outputlogic levels of the CHMOS device This is an importantconsideration if HMOSCHMOS interchangeabilitymust be maintained in an otherwise CMOS system

    HMOS 8051 outputs that have internal pullups (Ports1 2 and 3) typically reach 4V or more if IOH is zerobut not fast enough to meet timing specs Adding anexternal pullup resistor will ensure the logic level butstill not the timing as shown in Figure 23 If timing isan issue the best way to interface HMOS to CMOS isthrough a 74HCT circuit

    Idle and Power Down The Idle and Power Downmodes exist only on the CHMOS devices but if one

    27006825

    Figure 23 0-to-1 Transition Shows Unspecd

    Delay (Dt) in HMOS to 74HC Logic

    wishes to preserve the capability of interchangingHMOS and CHMOS 8051s the software has to be de-signed so that the HMOS parts will respond in an ac-ceptable manner when a CHMOS reduced power modeis invoked

    For example an instruction that invokes Power Downcan be followed by a JMP $

    CLR EAORL PCON2JMP $

    The CHMOS and HMOS parts will respond to thissequence of code differently The CHMOS part goinginto a normal CHMOS Power Down Mode will stopfetching instructions until it gets a hardware reset TheHMOS part will go through the motions of executingthe ORL instruction and then fetch the JMP instruc-tion It will continue fetching and executing JMP $ un-til hardware reset

    Maintaining HMOSCHMOS 8051 interchangeabilityin response to Idle requires more planning The HMOSpart will not respond to the instruction that puts theCHMOS part into Idle so that instruction needs to befollowed by a software idle This would be an idlingloop which would be terminated by the same conditionsthat would terminate the CHMOSs hardware IdleThen when the CHMOS device goes into Idle theHMOS version executes the idling loop until either ahardware reset or an enabled interrupt is received Nowif Idle is terminated by an interrupt execution for theCHMOS device will proceed after RETI from the in-struction following the one that invoked Idle The in-struction following the one that invoked Idle is theidling loop that was inserted for the HMOS device Atthis point both the HMOS and CHMOS devices mustbe able to fall through the loop to continue execution

    22

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    27/28

    AP-252

    One way to achieve the desired effect is to define afake Idle flag and set it just before going into IdleThe instruction that invoked Idle is followed by a soft-ware idle

    SETB IDLE

    ORL PCON1JB IDLE$

    Now the interrupt that terminates the CHMOSs Idlemust also break the software idle It does so by clearingthe Idle bit

    CLR IDLERETI

    Note too that the PCON register in the HMOS 8051contains only one bit SMOD whereas the PCON reg-ister in CHMOS contains SMOD plus four other bitsTwo of those other bits are general purpose flags Main-taining HMOSCHMOS interchangeability requiresthat these flags not be used

    REFERENCES1 Pawlowski Moroyan Alnether Inside CMOS

    Technology BYTE magazine Sept 1983 Avail-able as Article Reprint AR-302

    2 Kokkonen Pashley Modular Approach to C-MOS

    Technology Tailors Process to Application Elec-tronics May 1984 Available as Article ReprintAR-332

    3 Williamson T Designing Microcontroller Systemsfor Electrically Noisy Environments Intel Applica-

    tion Note AP-125 Feb 1982

    4 Williamson T PC Layout Techniques for Mini-mizing Noise Mini-Micro Southeast Session 9Jan 1984

    5 Alnether J High Speed Memory System Design Us-ing 2147H Intel Application Note AP-74 March1980

    6 Ott H Digital Circuit Grounding and Intercon-nection Proceedings of the IEEE Symposium on

    Electromagnetic Compatibility pp 292297 Aug1981

    7 Digital Sensors by Technar Technar Inc 205 North2nd Ave Arcadia CA 91006

    23

  • 7/31/2019 Designing with the 80C51BH - Application Note AP252 - 27006802

    28/28

    INTEL CORPORATION 2200 Mission College Blvd Santa Clara CA 95052 Tel (408) 765-8080

    INTEL CORPORATION (UK) Ltd Swindon United Kingdom Tel (0793) 696 000

    INTEL JAPAN kk Ibaraki-ken Tel 029747-8511

    Printed in USAxxxx0296B10Mxx xx