AP-252 APPLICATION NOTE Designing With The 80C51BH TOM WILLIAMSON MCO APPLICATIONS ENGINEER March 1985 Order Number: 270068-002 Information in this document is provided in connection with Intel products. Intel assumes no liability whatsoever, including infringement of any patent or copyright, for sale and use of Intel products except as provided in Intel's Terms and Conditions of Sale for such products. Intel retains the right to make changes to these specifications at any time, without notice. Microcomputer Products 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 and iCOMP trademarks has been issued to Intel Corporation. Contact your local Intel sales office or your distributor to obtain the latest specifications before placing your product order. Copies of documents which have an ordering number and are referenced in this document, or other Intel literature, may be obtained from: Intel Corporation P.O. Box 7641 Mt. Prospect, IL 60056-7641 or call 1-800-879-4683 COPYRIGHT (c) INTEL CORPORATION, 1996 DESIGNING WITH THE 80C51BH CONTENTS PAGE CMOS EVOLVES AAAAAAAAAAAAAAAAAAAAAAAAAA 1 WHAT IS CHMOS? AAAAAAAAAAAAAAAAAAAAAAAA 1 THE MCS-51 FAMILY IN CHMOS AAAAAAAAAA 1 LATCHUP AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 2 LOGIC LEVELS AND INTERFACING PROBLEMS AAAAAAAAAAAAAAAAAAAAAAAAAAAAA 2 NOISE CONSIDERATIONS AAAAAAAAAAAAAAAA 2 UNUSED PINS AAAAAAAAAAAAAAAAAAAAAAAAAAAAA 3 PULLUP RESISTORS AAAAAAAAAAAAAAAAAAAAAA 4 PULLDOWN RESISTORS AAAAAAAAAAAAAAAAA 4 DRIVE CAPABILITY OF THE INTERNAL PULLUPS AAAAAAAAAAAAAAAAAAA 5 POWER CONSUMPTION AAAAAAAAAAAAAAAAAA 6 Idle AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 7 Power Down AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 7 USING THE POWER DOWN MODE AAAAAAA 8 USING POWER MOSFETs TO CONTROL VCC AAAAAAAAAAAAAAAAAAAAAAAAAA 9 BATTERY BACKUP SYSTEMS AAAAAAAAAAAA 9 POWER SWITCHOVER CIRCUITS AAAAAAA 11 80C31BH a CHMOS EPROM AAAAAAAAAAAA 12 SCANNING A KEYBOARD AAAAAAAAAAAAAAA 13 DRIVING AN LCD AAAAAAAAAAAAAAAAAAAAAAAA 16 Using an LCD Driver AAAAAAAAAAAAAAAAAAAAAA 17 RESONANT TRANSDUCERS AAAAAAAAAAAA 18 Frequency Measurements AAAAAAAAAAAAAAAAA 18 Period Measurements AAAAAAAAAAAAAAAAAAAAA 20 Pulse Width Measurements AAAAAAAAAAAAAAA 21 HMOS/CHMOS INTERCHANGEABILITY AAAAAAAAAAAAAAA 21 External Clock Drive AAAAAAAAAAAAAAAAAAAAAA 21 Unused Pins AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 22 Logic Levels AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 22 Idle and Power Down AAAAAAAAAAAAAAAAAAAAAA 22 REFERENCES AAAAAAAAAAAAAAAAAAAAAAAAAAAA 23 AP-252 CMOS EVOLVES The original CMOS logic families were the 4000-series and the 74C-series circuits. The 74C-series circuits are functional equivalents to the corresponding numbered 74-series TTL circuits, but have CMOS logic levels and retain the other well known characteristics of CMOS logic. These characteristics are: low power consumption, high noise immunity, and slow speed. The low power consumption is inherent to the nature of the CMOS circuit. The noise immunity is due partly to the CMOS logic levels, and partly to the slowness of the circuits. The slow speed is due to the technology used to construct the transistors in the circuit. The technology used is called metal-gate CMOS, because the transistor gates are formed by metal deposition. More importantly, the gates are formed after the drain and source regions have been defined, and must overlap the source and drain somewhat to allow for alignment tolerances. This overlap plus the relatively large size of the transistors themselves result in high electrode capacitance, and that is what limits the speed of the circuit. High speed CMOS became feasible with the development of the self-aligning silicon gate technology. In this process polysilicon gates are deposited before the source and drain regions are defined. Then the source and drain regions are formed by ion implantation using the gate itself as a mask for the implantation. This eliminates most of the overlap capacitance. In addition, the process allows smaller transistors. The result is a significant increase in circuit speed. The 74HC-series of CMOS logic circuits is based on this technology, and has speeds comparable to LS TTL, which is to say about 10 times faster than the 74C-series circuits. The size reduction that contributes to the higher speed also demands an accompanying reduction in the maximum supply voltage. High-speed CMOS is generally limited to 6V. WHAT IS CHMOS? CHMOS is the name given to Intel's high-speed CMOS processes. There are two CHMOS processes, one based on an n-well structure and one based on a p-well structure. In the n-well structure, n-type wells are diffused into a p-type substrate. Then the n-channel transistors (nFETs) are built into the substrate and pFETs are built into the n-wells. In the p-well structure, p-type wells are diffused into an n-type substrate. Then the nFETs are built into the wells and pFETs, into the substrate. Both processes have their advantages and disadvantages, which are largely transparent to the user. Lower operating voltages are easier to obtain with the p-well structure than with the n-well structure. But the p-well structure does not easily adapt to an EPROM which would be pin-for-pin compatible with HMOS EPROMs. On the other hand the n-well structure can be based on the solidly founded HMOS process, in which nFETs are built into a p-type substrate. This allows somewhat more than half of the transistors in a CHMOS chip to be constructed by processes that are already well characterized. Currently Intel's CHMOS microcontrollers and memory products are n-well devices, whereas CHMOS microprocessors are p-well devices. Further discussion of the CHMOS technology is provided in References 1 and 2 (which are reprinted in the Microcontroller Handbook). THE MCSE-51 FAMILY IN CHMOS The 80C51BH is the CHMOS version of Intel's original 8051. The 80C31BH is the ROMless 80C51BH, equivalent to the 8031. These CHMOS devices are architecturally identical with their HMOS counterparts, except that they have two added features for reduced power. These are the Idle and Power Down modes of operation. In most cases, an 80C51BH can directly replace the 8051 in existing applications. It can execute the same code at the same speed, accept signals from the same sources, and drive the same loads. However, the 80C51BH covers a wider range of speeds, will emit CMOS logic levels to CMOS loads, and will draw about 1/10 the current of an 8051 (and less yet in the reduced power modes). Interchangeability between the HMOS and CHMOS devices is discussed in more detail in the final section of this Application Note. It should be noted that the 80C51BH CPU is not static. That means if the clock frequency is too low, the CPU might forget what it was doing. This is because the circuitry uses a number of dynamic nodes. A dynamic node is one that uses the note-to-ground capacitance to form a temporary storage cell. Dynamic nodes are used to reduce the transistor count, and hence the chip area, thus to produce a more economical device. This is not to say that the on-chip RAM in CHMOS microcontrollers is dynamic. It's not. It's the CPU that is dynamic, and that is what imposes the minimum clock frequency specification. 1 AP-252 LATCHUP Latchup is an SCR-type turn-on phenomenon that is the traditional nemesis of CMOS systems. The substrate, the wells, and the transistors form parasitic pnpn structures within the device. These parasitic structures turn on like an SCR if a sufficient amount of forward current is driven through one of the junctions. From the circuit designer's point of view it can happen whenever an input or output pin is externally driven a diode drop above VCC or below VSS, by a source that is capable of supplying the required trigger current. First, for equal supply voltages, CMOS gives (and requires) a higher ``logic 1'' level than TTL. Secondly, CMOS logic levels are VCC (or VDD) dependent, whereas guaranteed TTL logic levels are fixed when VCC is within TTL specs. Standard 74HC logic levels are as follows: VIHMIN e 70% of VCC VILMAX e 20% of VCC VOHMIN e VCC b 0.1V, lIOHl s 20 mA VOLMAX e 0.1V, lIOLl s 20 mA However much of a problem latchup has been in the past, it is good to know that in most recently developed CMOS devices, and specifically in CHMOS devices, the current required to trigger latchup is typically well over 100 mA. The 80C51BH is virtually immune to latchup. (References 1 and 2 present a discussion of the latchup mechanisms and the steps that are taken on the chip to guard against it.) Modern CMOS is not absolutely immune to latchup, but with trigger currents in the hundreds of mA, latchup is certainly a lot easier to avoid than it once was. Figure 1 compares 74HC, LS TTL, and 74HCT logic levels with those of the HMOS 8051 and the CHMOS 80C51BH for VCC e 5V. A careless power-up sequence might trigger a latchup in the older CMOS families, but it's unlikely to be a major problem in high-speed CMOS or in CHMOS. There is still some risk incurred in inserting or removing chips or boards in a CMOS system while the power is on. Also, severe transients, such as inductive kicks or momentary short-circuits, can exceed the trigger current for latchup. Since HMOS circuits were designed to be TTL-compatible, they have the same incompatibility. For applications in which some latchup risk seems unavoidable, you can put a small resistor (100X or so) in series with signal lines to ensure that the trigger current will never be reached. This also helps to control overshoot and RFI. LOGIC LEVELS AND INTERFACING PROBLEMS CMOS logic levels differ from TTL levels in two ways. Output logic levels depend of course on load current, and are normally specified at several load currents. When CMOS and TTL are powered by the same VCC, the logic levels guaranteed on the data sheets indicate that CMOS can drive TTL, but TTL can't drive CMOS. The incompatibility is that the TTL circuit's VOH level is too low to reliably be recognized by the CMOS circuit as a valid VIH. Fortunately, 74HCT-series circuits are available to ease these interfacing problems. They have TTL-compatible logic levels at the inputs and standard CMOS levels at the outputs. The 80C51BH is designed to work with either TTL or CMOS. Therefore its logic levels are specified very much like 74HCT circuits. That is, its input logic levels are TTL-compatible, and its output characteristics are like standard high-speed CMOS. NOISE CONSIDERATIONS One of the major reasons for going to CMOS has traditionally been that CMOS is less susceptible to noise. As previously noted, its low susceptibility to noise is VCC e 5V Logic State 74HC 74HCT LS TTL 8051 80C51BH VIH VIL 3.5V 1.0V 2.0V 0.8V 2.0V 0.8V 2.0V 0.8V 1.9V 0.9V VOH VOL 4.9V 0.1V 4.9V 0.1V 2.7V 0.5V 2.4V 0.45V 4.5V 0.45V 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 AP-252 partly due to superior noise margins, and partly due to its slow speed. Noise margin is the difference between VOL and VIL, or between VOH and VIH. If VOH from a driving circuit is 2.7V and VIH to the driven circuit is 2.0V, then the driven circuit has 0.7V of noise margin at the logic high level. These kinds of comparisons show that an all-CMOS system has wider noise margins than an allTTL system. Figure 2 shows noise margins in CMOS and LS TTL systems when both have VCC e 5V. It can be seen that CMOS/CMOS and CMOS/CHMOS systems have an edge over LS TTL in this respect. Noise margins can be misleading, however, because they don't say how much noise energy it takes to induce in the circuit a noise voltage of sufficient amplitude to cause a logic error. This would involve consideration of the width of the noise pulse as compared with the circuit's response speed, and the impedance to ground from the point of noise introduction in the circuit. When these considerations are included, it is seen that using the slower 74C- and 4000-series circuits with a 12 or 15V supply voltage does offer a truly improved level of noise immunity, but that high-speed CMOS at 5V is not significantly better than TTL. current in extremely sharp spikes at the clock edges. The VHF and UHF components of these spikes are not drawn from the power supply, but from the decoupling capacitor. If the decoupling circuit is not sufficiently low in inductance, VCC will glitch at each clock edge. We suggest that a 0.1 mF decoupler cap be used in a minimum-inductance configuration with the microcontroller. A minimum-inductance configuration is one that minimizes the area of the loop formed by the chip (VCC to VSS), the traces to the decoupler cap, and the decoupler cap. PCB designers too often fail to understand that if the traces that connect the decoupler cap to the VCC and VSS pins aren't short and direct, the decoupler loses much of its effectiveness. Overshoot and ringing in signal lines are potential sources of logic upsets. These can largely be controlled by circuit layout. Inserting small resistors (about 100X) in series with signal lines that seem to need them will also help. The sharp edges produced by high-speed CMOS can cause RFI problems. The severity of these problems is largely a function of the PCB layout. We don't mean to imply that all RFI problems can be solved by a better PCB layout. It may well be, for example, that in some RFI-sensitive designs high-speed CMOS is simply not the answer. But circuit layout is a critical factor in the noise performance of any electronic system, and more so in high-speed CMOS systems than others. One should not mistake the wider supply voltage tolerance of high-speed CMOS for VCC glitch immunity. Supply voltage tolerance is a DC rating, not a glitch rating. Circuit layout techniques for minimizing noise susceptibility and generation are discussed in References 3 through 6. For any clocked CMOS, and most especially for VLSI CMOS, VCC decoupling is critical. CHMOS draws UNUSED PINS Interface Noise Margin for VCC e 5V Logic Low VIL -VOL Logic High VOH -VIH 74HC to 74HC 0.9V 1.4V LSTTL to LSTTL 0.3V 0.7V LSTTL to 74HCT 0.3V 0.7V LSTTL to 80C51BH 0.3V 0.7V 74HC to 80C51BH 0.8V 3.0V 80C51BH to 74HC 0.8V 1.0V Figure 2. Noise Margins for CMOS and LS TTL Circuits CMOS input pins should not be left to float, but should always be pulled to one logic level or the other. If they float, they tend to float into the transition region between 0 and 1, where the pullup and pulldown devices in the input buffer are both conductive. This causes a significant increase in ICC. A similar effect exists in HMOS circuits, but with less noticeable results. In 80C51BH and 80C31BH designs, unused pins of Ports 1, 2, and 3 can be ignored, because they have internal pullups that will hold them at a valid Logic 1 level. Port 0 pins are different, however, in not having internal pullups (except during bus operations). When the 80C51BH is in reset, the Port 0 pins are in a float state unless they are externally pulled up or down. If it's going to be held in reset for just a short time, the transient float state can probably be ignored. When it comes out of reset, the pins stay afloat unless 3 AP-252 they are externally pulled either up or down. Alternatively, the software can internally write 0s to whatever Port 0 pins may be unused. The same considerations are applicable to the 80C31BH with regards to reset. But when the 80C31BH comes out of reset, it commences bus operations, during which the logic levels at the pins are always well defined as high or low. Consider the 80C31BH in the Power Down or Idle modes, however. In those modes it is not fetching instructions, and the Port 0 pins will float if not externally pulled high or low. The choice of whether to pull them high or low is the designer's. Normally it is sufficient to pull them up to VCC with 10k resistors. But if power is going to be removed from circuits that are connected to the bus, it will be advisable to pull the bus pins down (normally with 10k resistors). Considerations involved in selecting pullup and pulldown resistor values are as follows. PULLUP RESISTORS If a pullup resistor is to be used on a Port 0 pin, its minimum value is determined by IOL requirements. If the pin is trying to emit a 0, then it will have to sink the current from the pullup resistor plus whatever other current may be sourced by other loads connected to the pin, as shown in Figure 3a, while maintaining a valid output low (VOL). To guarantee that the pin voltage will not exceed 0.45V, the resistor should be selected so that IOL doesn't exceed the value specified on the data sheet. In most CMOS applications, the minimum value would be about 2k X. The maximum value you could use depends on how fast you want the pin to pull up after bus operations have ceased, and how high you want the VOH level to be. The smaller the resistor the faster it pulls up. Its effect on the VOH level is that VOH e VCC b (ILI a IIH) c R. ILI is the input leakage current to the Port 0 pin, and IIH is the input high current to the external loads, as shown in Figure 3b. Normally VOH can be expected to reach 0.9 VCC if the pullup resistance does not exceed about 50k X. Pulldown Resistors 270068 - 1 Figure 3a. Conditions defining the minimum value for R. P0.X is emitting a logic low. R must be large enough to not cause IOL to exceed data sheet specifications. If a pulldown resistor is to be used on a Port 0 pin, its minimum value is determined by VOH requirements during bus operations, and its maximum value is in most cases determined by leakage current. During bus operations the port uses internal pullups to emit 1s. The D.C. Characteristics in the data sheet list guaranteed VOH levels for given IOH currents. (The ``-'' sign in the IOH value means the pin is sourcing that current to the external load, as shown in Figure 4.) To ensure the VOH level listed in the data sheet, the resis- 270068 - 2 Figure 3b. Conditions defining the maximum value for R. P0.X is in a high impedance state. R must be small enough to keep VOH acceptably high. 4 270068 - 3 Figure 4a. Conditions defining the minimum value for R. P0.X is emitting a 1 in a bus operation. R must be large enough to not cause IOH to exceed data sheet specifications. AP-252 VOH a IIH s l IOH l R DRIVE CAPABILITY OF THE INTERNAL PULLUPS tor has to satisfy where IIH is the input high current to the external loads. When the pin goes into a high impedance state, the pulldown resistor will have to sink leakage current from the pin, plus whatever other current may be sourced by other loads connected to the pin, as shown in Figure 4b. The Port 0 leakage current is ILI on the data sheet. The resistor should be selected so that the voltage developed across it by these currents will be seen as a logic low by whatever circuits are connected to it (including the 80C51BH). In CMOS/CHMOS applications, 50k X is normally a reasonable maximum value. 270068 - 4 Figure 4b. Conditions defining the maximum value for R. P0.X is in a high impedance state. R must be small enough to keep VOL acceptably low. There's an important difference between HMOS and CHMOS port drivers. The pins of Ports 1, 2, and 3 of the CHMOS parts each have three pullups: strong, normal, and weak, as shown in Figure 5. The strong pullup (p1) is only used during 0-to-1 transitions, to hasten the transition. The weak pullup (p2) is on whenever the bit latch contains a 1. The ``normal'' pullup (p3) is controlled by the pin voltage itself. The reason that p3 is controlled by the pin voltage is that if the pin is being used as an input, and the external source pulls it to a low, then turning off p3 makes for a lower IIL. The data sheet shows an ``ITL'' specification. This is the current that p3 will source during the time the pin voltage is making its 1-to-0 transition. This is what IIL would be if an input low at the pin didn't turn p3 off. Note, however, that this p3 turn-off mechanism puts a restriction on the drive capacity of the pin if it's being used as an output. If you're trying to output a logic high, and the external load pulls the pin voltage below the pin's VIHMIN spec, p3 might turn off, leaving only the weak p2 to provide drive to the load. To prevent this happening, you need to ensure that the load doesn't draw more than the IOH spec for a valid VOH. The idea is to make sure the pin voltage never falls below its own VIHMIN specification. 270068 - 5 Figure 5. 80C51BH Output Drivers for Ports 1, 2 and 3 5 AP-252 POWER CONSUMPTION The main reason for going to CMOS, of course, is to conserve power. (There are other reasons, but this is the main one.) Conserving power doesn't mean just reducing your electric bill. Nor does it necessarily relate to battery operation, although battery operation without CMOS is pretty unhandy. The main reason for conserving power is to be able to put more functionality into a smaller space. The reduced power consumption allows the use of smaller and lighter power supplies, and less heat being generated allows denser packaging of circuit components. Expensive fans and blowers can usually be eliminated. A cooler running chip is also more reliable, since most random and wearout failures relate to die temperature. And finally, the lower power dissipation will allow more functions to be integrated onto the chip. The reason CMOS consumes less power than NMOS is that when it's in a stable state there is no path of conduction from VCC to VSS except through various leakage paths. CMOS does draw current when it's changing states. How much current it draws depends on how often and how quickly it changes states. 270068 - 6 CMOS circuits draw current in sharp spikes during logical transitions. These current spikes are made up of two components. One is the current that flows during the transition time when pullup and pulldown FETs are both active. The average (DC) value of this component is larger when the transition times of the input signals are longer. For this reason, if the current draw is a critical factor in the design, slow rise and fall times should be avoided, even when the system speed doesn't seem to justify a need for nanosecond switching speeds. The other component is the current that charges stray and load capacitance at the nodes of a CMOS logic gate. The average value of this current spike is its area (integral over time) multiplied by its rep rate. Its area is the amount of charge it takes to raise the node capacitance, C, to VCC. That amount of charge is just C x VCC. So the average value of the current spike is C x VCC x f, where f is the clock frequency. This component of current increases linearly with clock frequency. For minimal current draw, the 80C52BH-2 is spec'd to run at frequencies as low as 500 kHz. Keep in mind, though, that other component of current that is due to slow rise and fall times. A sinusoid is not the optimal waveform to drive the XTAL1 pin with. Yet crystal oscillators, including the one on the 80C51BH, generate sinusoidal waveforms. Therefore, if the on-chip oscillator is being used, you can expect the device to draw more current at 500 kHz, than it does at 1.5 MHz, as shown in Figure 6. If you derive a good sharp square wave from an external oscillator, and use that to drive XTAL1, then the microcontroller will draw less current. But the external oscillator will probably make up the difference. The 80C51BH has two power-saving features not available in the HMOS devices. These are the Idle and Power Down modes of operation. The on-chip hardware that implements these reduced power modes is shown in Figure 7. Both modes are invoked by software. Figure 6. 80C51BH ICC vs. Clock Frequency 270068 - 7 Figure 7. Oscillator and Clock Circuitry Showing Idle and Power Down Hardware 6 AP-252 Idle: In the Idle Mode (IDL e 0 in Figure 7), the CPU puts itself to sleep by gating off its own clock. It doesn't stop the oscillator. It just stops the internal clock signal from getting to the CPU. Since the CPU draws 80 to 90 percent of the chip's power, shutting it off represents a fairly significant power savings. The on-chip periperals (timers, serial port, interrupts, etc.) and RAM continue to function as normal. The CPU status is preserved in its entirety: the Stack Pointer, Program Counter, Program Status Word, Accumulator, and all other registers maintain their data during Idle. The Idle Mode is invoked by setting bit 0 (IDL) of the PCON register. PCON is not bit-addressable, so the bit has to be set by a byte operation, such as ORL PC0N,#1 The PCON register also contains flag bits GF0 and GF1, which can be used for any general purposes, or to give an indication if an interrupt occurred during normal operation or during Idle. In this application, the instruction that invokes Idle also sets one or both of the flag bits. Their status can then be checked in the interrupt routines. While the device is in the Idle Mode, ALE and PSEN emit logic high (VOH), as shown in Figure 8. This is so external EPROM can be deselected and have its output disabled. The port pins hold the logical states they had at the time the Idle was activated. If the device was executing out of external program memory, Port 0 is left in a high impedance state and Port 2 continues to emit the high byte of the program counter (using the strong pullups to emit 1s). If the device was executing out of internal program memory, Ports 0 and 2 continue to emit whatever is in the P0 and P2 registers. PSEN/ The other way is with a hardware reset. Since the clock oscillator is still running, RST only needs to be held active for two machine cycles (24 oscillator periods) to complete the reset. Note that this exit from Idle writes 1s to all the ports, initializes all SFRs to their reset values, and restarts program execution from location 0. Power Down: In the Power Down Mode (PD e 0 in Figure 7), the CPU puts the whole chip to sleep by turning off the oscillator. In case it was running from an external oscillator, it also gates off the path to the internal phase generators, so no internal clock is generated even if the external oscillator is still running. The on-chip RAM, however, saves its data, as long as VCC is maintained. In this mode the only ICC that flows is leakage, which is normally in the micro-amp range. The Power Down Mode is invoked by setting bit 1 in the PCON register, using a byte instruction such as ORL PCON,#2 While the device is in Power Down, ALE and PSEN emit lows (VOL), as shown in Figure 8. The reason they are designed to emit lows is so that power can be removed from the rest of the circuit, if desired, while the 80CS51BH is in its Power Down mode. The port pins continue to emit whatever data was written to them. Note that Port 2 emits its P2 register data even if execution was from external program memory. Internal Execution Pin ALE There are two ways to terminate Idle. Activation of any enabled interrupt will cause the hardware to clear bit 0 of the PCON register, terminating the Idle mode. The interrupt will be serviced, and following RETI the next instruction to be executed will be the one following the instruction that invoked Idle. External Execution Idle Power Down Idle Power Down 1 0 1 0 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 AP-252 Port 0 also emits its P0 register data, but if execution was from external program memory, the P0 register data is FF. The oscillator is stopped, and the part remains in this state as long as VCC is held, and until it receives an external reset signal. The only exit from Power Down is a hardware reset. Since the oscillator was stopped, RST must be held active long enough for the oscillator to re-start and stabilize. Then the reset function initializes all the Special Function Registers (ports, timers, etc.) to their reset values, and re-starts the program from location 0. Therefore, timer reloads, interrupt enables, baud rates, port status, etc. need to be re-established. Reset does not affect the content of the on-chip data RAM. If VCC was held during Power Down, the RAM data is still good. USING THE POWER DOWN MODE The software-invoked Power Down feature offers a means of reducing the power consumption to a mere trickle in systems which are to remain dormant for some period of time, while retaining important data. The user should give some thought to what state the port pins should be left in during the time the clock is stopped, and write those values to the port latches before invoking Power Down. If VCC is going to be held to the entire circuit, one would want to write values to the port latches that would deselect peripherals before invoking Power Down. For example, if external memory is being used, the P2 SFR should be loaded with a value which will not generate an active chip select to any memory device. In some applications, VCC to part of the system may be shut off during Power Down, so that even quiescent and standby currents are eliminated. Signal lines that connect to those chips must be brought to a logic low, whether the chip in question is CMOS, NMOS, or TTL, before VCC is shut off to them. CMOS pins have parasitic pn junctions to VCC, which will be forward biased if VCC is reduced to zero while the pin is held at a logic high. NMOS pins often have FETs that look like diodes to VCC. TTL circuits may actually be damaged by an input high if VCC e 0. That's why the 80C51BH outputs lows at ALE and PSEN during Power Down. Figure 9 shows a circuit that can be used to turn VCC off to part of the system during Power Down. The circuit will ensure that the secondary circuit is not de-energized until after the 80C31BH is in Power Down, and that the 80C31BH does not receive a reset (terminating the Power Down mode) before the secondary circuit is re-energized. Therefore, the program memory itself can be part of the secondary circuit. 270068 - 8 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 AP-252 In Figure 9, when VCC is switched on to the 80C31BH, capacitor C1 provides a power-on reset. The reset function writes 1s to all the port pins. The 1 at P2.6 turns Q1 on, enabling VCC to the secondary circuit through transistor Q2. As the 80C31BH comes out of reset, Port 2 commences emitting the high byte of the Program Counter, which results in the P2.7 and P2.6 pins outputting 0s. The 0 at P2.7 ensures continuation of VCC to the secondary circuit. The system software must now write a 1 to P2.7 and a 0 to P2.6 in the Port 2 SFR, P2. These values will not appear at the Port 2 pins as long as the device is fetching instructions from external program memory. However, whenever the 80C31BH goes into Power Down, these values will appear at the port pins, and will shut off both transistors, disabling VCC to the secondary circuit. Closing the switch S1 re-energizes the secondary circuit, and at the same time sends a reset through C2 to the 80C31BH to wake it up. The diode D1 is to prevent C1 from hogging current from C2 during this secondary reset. D2 prevents C2 from discharging through the RST pin when VCC to the secondary circuit goes to zero. 270068 - 9 a. Using a pFET USING POWER MOSFETs to CONTROL VCC Power MOSFETs are gaining in popularity (and availability). The easiest way to control VCC is with a Logic Level pFET, as shown in Figure 10a. This circuit allows the full VCC to be used to turn the device on. Unfortunately, power pFETs are not economically competitive with bipolar transistors of comparable ratings. Power nFETs are both economical and available, and can be used in this application if a DC supply of higher voltage is available to drive the gate. Figure 10b shows how to implement a VCC switch using a power nFET and a (nominally) a 12V supply. The problem here is that if the device is on, its source voltage is a 5V. To maintain the on state, the gate has to be another 5 or 10V above that. The ``12V'' supply is not particularly critical. A minimally filtered, unregulated rectifier will suffice. BATTERY BACKUP SYSTEMS Here we consider circuits that normally draw power from the AC line, but switch to battery operation in the event of a power failure. We assume that in battery operation high-current loads will be allowed to die along with the AC power. The system may continue then with reduced functionality, monitoring a control transducer, perhaps, or driving an LCD. Or it may go into a bare-bones survival mode, in which critical data is saved but nothing else happens till AC power is restored. In any case it is necessary to have some early warning of an impending power failure so that the system can arrange an orderly transfer to battery power. Early warning systems can operate by monitoring either the AC line voltage or the unregulated rectifier output, or even by monitoring the regulated DC voltage. Monitoring the AC line voltage gives the earliest warning. That way you can know within one or two half-cycles of line frequency that AC power is down. In most cases you then have at least another half-cycle of line frequency before the regulated VCC starts to fall. In a half-cycle of line frequency an 80C51BH can execute about 5,000 instructionsplenty of time to arrange an orderly transfer of power. 270068 - 28 b. Using an nFET Figure 10. Using Power MOSFETs to Control VCC2 The circuit in Figure 11 uses a Zener diode to test the line voltage each half-cycle, and a junction transistor to pass the information on to the 80C51BH. (Obviously a voltage comparator with a suitable reference source can 9 AP-252 270068 - 10 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 it works is if the line voltage reaches an acceptably high level, it breaks over Z1, drives Q1 to saturation, and interrupts the 80C51BH. The interrupt would be transition-activated, in this application. The interrupt service routine reloads one of the C51BH's timers to a value that will make it roll over in something between one and two half-cycles of line frequency. As long as the line voltage is healthy, the timer never rolls over, because it is reloaded every half-cycle. If there is a single half-cycle in which the line voltage doesn't reach a high enough level to generate the interrupt, the timer rolls over and generates a timer interrupt. The timer interrupt then commences the transition to battery backup. Critical data needs to be copied into protected RAM. Signals to circuits that are going to lose power must be written to logic low. Protected circuits (those powered by VCC2) that communicate with unprotected circuits must be deselected. The microcontroller itself may be put into Idle, so that it can continue some level of interrupt-driven functionality, or it may be put into Power Down. Note that if the CPU is going to invoke Power Down, the Special Function Registers may also need to be copied into protected RAM, since the reset that terminates the Power Down mode will also intialize all the SFRs to their reset values. The circuit in Figure 11 does not show a wake-up mechanism. A number of choices are available, however. A pushbutton could be used to generate an interrupt, if the CPU is in Idle, or to activate reset, if the CPU is in Power Down. 10 Automatic wake-up on power restoration is also possible. If the CPU is in Idle, it can continue to respond to any interrupts that might be generated by Q1. The interrupt service routine determines from the status of flag bits GF0 and GF1 in PCON that it is in Idle because there was a power outage. It can then sample VCC1 through a voltage comparator similar to Z1, Q1 in Figure 11. A satisfactory level of VCC1 would be indicated by the transistor being in saturation. But perhaps you can't spare the timer that is the key to the operation of the circuit in Figure 11. In that case a retriggerable one-shot, triggered by the AC line voltage, can perform essentially the same function. Figure 12 shows an example of this type of power failure detector. A retriggerable one-shot (one half of a 74HC123) monitors the AC line voltage through transistor Q1. Q1 retriggers the one-shot every half-cycle of line frequency. If the output pulse width is between one and two halfcycles of line frequency, then a single missing or low half-cycle will generate an active low warning flag, which can be used to interrupt the microcontroller. The interrupt routine takes care of the transition to battery backup. From this point VCC1 may or may not actually drop out. The missing half-cycle of line voltage that caused the power down sequence may have been nothing more than a short glitch. If the AC line comes back strong enough to trigger the one-shot while VCC1 is still up (as indicated by the state of transistor Q2), then the other half of the 74HC123 will generate a wake-up signal. AP-252 270068 - 11 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 awake for at least another half-cycle of line frequency (another 5,000 or so instructions) before possibly being told to arrange another transfer of power. Consequently, if the line voltage is jittering erratically around the switchover point (determined by diode Z1), the system will limp along executing in half-cycle units of line frequency. On the other hand, if the power outage is real and lengthy, VCC1 will eventually fall below the level at which the backup battery takes over. The backup battery maintains power to the 80C51BH, and to the 74HC123, and to whatever other circuits are being protected during this outage. The battery voltage must be high enough to maintain VCCMIN specs to the 80C51BH. If the microcontroller is an 80C31BH, executing out of external ROM, and if the C31BH is put into Idle during the power outage, then the external ROM must also be supplied by the battery. On the other hand, if the C31BH is put into Power Down during the outage, then the ROM can be allowed to die with the AC power. The considerations here are the same as in Figure 9: VCC to the ROM is still up at the time Power Down is invoked, and we must ensure (through selection of diode Z2 in Figure 12) that the 80C31BH is not awakened till ROM power is back in spec. POWER SWITCHOVER CIRCUITS Battery backup systems need to have a way for the protected circuits to draw power from the line-operated power supply when that source is available, and to switch over to battery power when required. The switchover circuit is simple if the entire system is to be battery powered in the event of a line power outage. In that case a pair of diodes suffice, as shown in Figure 12, provided VCCMIN specs are still met after the diode drop has been subtracted from its respective power source. The situation becomes more complicated when part of the circuit is going to be allowed to die when the AC power goes out. In that case it is difficult to maintain equal VCCs to protected and unprotected circuits (and possibly dangerous not to). The problem can be alleviated by using a Schottky diode instead of a 1N4001, for its lower forward voltage drop. The 1N5820, for example, has a foward drop of about 0.35V at 1A. Other solutions are to use a transistor or power MOSFET switch, as shown in Figure 13. With minor modifications this switch can be controlled by port pins. 11 AP-252 cations, the 2764's Chip Enable (CE) pin is hardwired to ground (since it's normally the only program memory on the bus). This can be done with the CHMOS versions as well, but there is some advantage in connecting CE to ALE, as shown in Figure 14a. The advantage is that if the 80C31BH is put into Idle mode, since ALE goes to a 1 in that mode, the 27C64 will be deselected and go into a low current standby mode. 270068 - 27 a. Using a pnp Transistor The timing waveforms for this configuration are shown in Figure 14b. In Figure 14b the signals and timing parameters in parenthesis are those of the 27C64, and the others are of the 80C31BH, except Tprop is a parameter of the address latch. The requirements for timing compatibility are TAVIV b Tprop l tACC TLLIV l tCE TPLIV l tOE TPXIZ l tDF 270068 - 12 b. Using a Power MOSFET Figure 13. Power Switchover Ckts. 80C31BH a CHMOS EPROM The 27C64 and 87C64 are Intel's 8K byte CHMOS EPROMs. The 27C64 requires an external address latch, and can be used with the 80C31BH as shown in Figure 14a. In most 8031 a 2764 (HMOS) appli- If the application is going to use the Power Down mode then we have another consideration: In Idle, ALE e PSEN e 1, and in Power Down, ALE e PSEN e 0. In a realistic application there are likely to be more chips in the circuit than are shown in Figure 14, and it is likely that the nonessential ones will have their VCC removed while the CPU is in Power Down. In that case the EPROM and the address latch should be among the chips that have VCC removed, and logic lows are exactly what are required at ALE and PSEN. But if VCC is going to be maintained to the EPROM during Power Down, then it will be necessary to de- 270068 - 26 Figure 14a. 80C31BH a 27C64 12 AP-252 The 87C64 is like the 27C64 except that it has an onchip address latch. The Port 0 pins are tied to both address and data pins of the 87C64, as shown in Figure 16a. ALE drives the EPROM's ALE/CS input. During ALE high, the address information is allowed to flow into the EPROM and begin accessing the code byte. On the falling edge of ALE the address byte is internally latched. The A0 - A7 inputs are then ignored and the same bus lines are used to transmit the fetched code byte from the O0 - O7 pins back to the 80C31BH. The timing waveforms for this configuration are shown in Figure 16b. In Figure 16b the signals and timing parameters in parentheses are those of the 87C64, and the others are of the 80C31BH. The requirements for timing compatibility are 270068 - 13 Figure 14b. Timing Waveforms for 80C31BH a 27C64 select the EPROM when the CPU is in Power Down. If Idle is never invoked, CE of the EPROM can be connected to P2.7 of the 80C31BH, as shown in Figure 15a. In normal operation, P2.7 will be emitting the MSB of the Program Counter, which is 0 if the program contains less than 32K of code. Then when the CPU goes into Power Down, the Port 2 pins emit P2 SFR data, which puts a 1 at P2.7, thus deselecting the EPROM. If Idle and Power Down are both going to be used, CE of the EPROM can be driven by the logical OR of ALE and P2.7, as shown in Figure 15b. In Idle, ALE e 1 will deselect the EPROM, and in Power Down, P2.7 e 1 will deselect it. 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 the 27C64 with regards to the Idle and Power Down modes. Basically you want CS e 1 if VCC is maintained to the EPROM, and CS e OE e 0 if VCC is removed. SCANNING A KEYBOARD 270068 - 14 a. Power Down is used but not idle. 270068 - 15 b. Idle and Power Down both used. Figure 15. Modifications to 80C31BH/27C64 Interface Pulldown resistors are shown in Figure 14a under the assumption that something on the bus is going to have its VCC removed during Power Down. If this is not the case, pullups can be used as well as pulldowns. There are many different kinds of keyboards, but alphanumeric keyboards generally consist of a matrix of 8 scan lines and 8 receive lines as shown in Figure 17. Each set of lines connects to one port of the microcontroller. The software has written 0s to the scan lines, and 1s to the receive lines. Pressing a key connects a scan line to a receive line, thus pulling the receive line to a logic low. The 8 receive lines are ANDed to one of the external interrupt pins, so that pulling any of the receive lines low generates an interrupt. The interrupt service routine has to identify the pressed key, if only one key is down, and convert that information to some useful output. If more than one key in the line matrix is found to be pressed, no action is taken. (This is a ``two key lockout'' scheme.) 13 AP-252 On some keyboards, certain keys (Shift, Control, Escape, etc.) are not a part of the line matrix. These keys would connect directly to a port pin on the microcontroller, and would not cause lock-out if pressed simultaneously with a matrix key, nor generate an interrupt if pressed singly. Normally the microcontroller would be in idle mode when a key has not been pressed, and another task is not in progress. Pressing a matrix key generates an in- terrupt, which terminates the Idle. The interrupt service routine would first call a 30 ms (or so) delay to debounce the key, and then set about the task of identifying 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 but one of the lines would be read as 1s. Then 0s are written to the receive lines and 1s to the scan lines, and the scan lines are read. If a single key is down, all but one of 270068 - 16 Figure 16a. 80C31BH a 87C64 270068 - 17 Figure 16b. Timing Waveforms for 80C31BH a 87C64 14 AP-252 these lines would be read as 1s. By locating the single 0 in each set of lines, the pressed key can be identified. If more than one matrix key is down, one or both sets of lines 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 is 0. Figure 18 shows a subroutine (SCAN) which does that using the 8051's bit-addressing capability. To use the subroutine, move the line data into a bit-addressable RAM location named LINE, and call the SCAN routine. The number of LINE bits which are zero is returned in ZEROCOUNTER. If only one bit is zero, its number (1 through 8) is returned in ZERO BIT. The interrupt service routine that is executed in response to a key closure might then be as follows: RESPONSE TO KEY CLOSURE: CALL DEBOUNCE DELAY MOV LINE,P1; ;See Figure 17. CALL SCAN DJNZ ZERO COUNTER,REJECT MOV ADDRESS,ZERO BIT MOV P2,#0FFH; ;See Figure 17. MOV P1,#0 MOV LINE,P2 CALL SCAN DJNZ ZERO COUNTER,REJECT XCH A,ZERO BIT SWAP A ORL ADDRESS,A XCH A,ZERO BIT MOV P1,#0FFH MOV P2,#O REJECT: CLR EX0 RETI 270068 - 18 Figure 17. Scanning a Keyboard 15 AP-252 270068 - 19 Figure 18. Subroutine SCAN Determines Which of 8 Bits in LINE is Zero Notice that RESPONSETOKEYCLOSURE does not change the Accumulator, the PSW, nor any of the registers R0 through R7. Neither do SCAN or DEBOUNCEDELAY. What we come out with then is a one-byte key address (ADDRESS) which identifies the pressed key. The key's scan line number is in the upper nibble of ADDRESS, and its receive line number is in the lower nibble. ADDRESS can be used in a look-up table to generate a key code to transmit to a host computer, and/or to a display device. The keyboard interrupt itself must be edge-triggered, rather than level-activated, so that the interrupt routine is invoked when a key is pressed, and is not constantly being repeated as long as the key is held down. In edgetriggered mode, the on-chip hardware clears the interrupt flag (EX0, in this case) as the service routine is being vectored to. In this application, however, contact bounce will cause several more edges to occur after the service routine has been vectored to, during the DEBOUNCEDELAY routine. Consequently it is necessary to clear EX0 again in software before executing RETI. The debounce delay routine also takes advantage of the Idle mode. In this routine a timer must be preloaded with a value appropriate to the desired length of delay. This would be timer preload e 16 (osc kHz) c (delay time ms) 12 For example, with a 3.58 MHz oscillator frequency, a 30 ms delay could be obtained using a preload value of b 8950, or DD0A, in hex digits. In the debounce delay routine (Figure 19), the timer interrupt is enabled and set to a higher priority than the keyboard interrupt, because as we invoke Idle, the keyboard interrupt is still ``in progress''. An interrupt of the same priority will not be acknowledged, and will not terminate the Idle mode. With the timer interrupt set to priority 1, while the keyboard interrupt is a priority 0, the timer interrupt, when it occurs, will be acknowledged and will wake up the CPU. The timer interrupt service routine does not itself have to do anything. The service routine might be nothing more than a single RETI instruction. RETI from the timer interrupt service routine then returns execution to the debounce delay routine, which shuts down the timer and returns execution to the keyboard service routine. DRIVING AN LCD An LCD (Liquid Crystal Display) consists of a backplane and any number of segments or dots which will be used to form the image being displayed. Applying a voltage (nominally 4 or 5V) between any segment and the backplane causes the segment to darken. The only catch is that the polarity of the applied voltage has to be periodically reversed, or else a chemical reac- AP-252 270068 - 20 Figure 19. Subroutine DEBOUNCEDELAY Puts the 80C51BH into Idle During the Delay Time tion takes place in the LCD which causes deterioration and eventual failure of the liquid crystal. To prevent this happening, the backplane and all the segments are driven with an AC signal, which is derived from a rectangular voltage waveform. If a segment is to be ``off'' it is driven by the same waveform as the backplane. Thus it is always at backplane potential. If the segment is to be ``on'' it is driven with a waveform that is the inverse of the backplane waveform. Thus it has about 5V of periodically changing polarity between it and the backplane. With a little software overhead, the 80C51BH can perform this task without the need for additional LCD drivers. The only drawback is that each LCD segment uses up one port pin, and the backplane uses one more. If more than, say, two 7-segment digits are being driven, there aren't many port pins left for other tasks. Nevertheless, assuming a given application leaves enough port pins available to support this task, the considerations for driving the LCD are as follows. Suppose, for example, it is a 2-digit display with a decimal point. One port (TENSDIGIT) connects to the 7 segments of the tens digit plus the backplane. Another port (ONESDIGIT) connects to a decimal point plus the 7 segments of the ones digit. tasks are not requiring servicing. When the timer rolls over it generates an interrupt, which brings the 80C51BH out of Idle. The service routine reloads the timer (for the next rollover), and inverts the logic levels of all the pins that are connected to the LCD. It might look like this: LCD DRIVE INTERRUPT: MOV TL1,#LOW( 1 XTAL FREQ) MOV TH1,#HIGH( 1 XTAL FREQ) XRL TENS DIGIT,#0FFH XRL ONES DIGIT,#0FFH RETI To update the display, one would use a look-up table to generate the characters. In the table, ``on'' segments are represented as 1s, and ``off'' segments as 0s. The backplane bit is represented as a 0. The quantity to be displayed is stored in RAM as a BCD value. The look-up table operates on the low nibble of the BCD value, and produces the bit pattern that is to be written to either the ones digit or the tens digit. Before the new patterns can be written to the LCD, the LCD drive interrupt has to be disabled. That is to prevent a polarity reversal from taking place between the times the two digits are written. An update subroutine is shown in Figure 20. USING AN LCD DRIVER One of the 80C51BH's timers is used to mark off halfperiods of the drive voltage waveform. The LCD drive waveform should have a rep rate between 30 and 100 Hz, but it's not very critical. A half-period of 12 ms will set the rep rate to about 42 Hz. The preload/reload value to get 12 ms to rollover is the 2's complement negative of the oscillator frequency in kHz: if the oscillator frequency is 3.58 MHz, the reload value is b 3580, or F204 in hex digits. Now, the 80C51BH would normally be in Idle, to conserve power, during the time that the LCD and other As was noted, driving an LCD directly with an 80C51BH uses a lot of port pins. LCD drivers are available in CMOS to interface an 80C51BH to a 4-digit display using only 7 of the C51BH's I/O pins. Basically, the C51BH tells the LCD driver what digit is to be displayed (4 bits) and what position it is to be displayed in (2 bits), and toggles a Chip Select pin to tell the driver to latch this information. The LCD driver generates the display characters (hex digits), and takes care of the polarity reversals using its own RC oscillator to generate the timing. 17 AP-252 Figure 21a shows an 80C51BH working with an ICM7211M to drive a 4-digit LCD, and the software that updates the display. One could equally well send information to the LCD driver over the bus. In that case, one would set up the Accumulator with the digit select and data input bits, and execute a MOVX @ R0,A instruction. The LCD driver's chip select would be driven by the CPU's WR signal. This is a little easier in software than the direct bit manipulation shown in Figure 21a. However, it uses more I/O pins, unless there is already some external memory involved. In that case, no extra pins are used up by adding the LCD driver to the bus. RESONANT TRANSDUCERS Analog transducers are often used to convert the value of a physical property, such as temperature, pressure, etc., to an analog voltage. These kinds of transducers then require an analog-to-digital converter to put the measurement into a form that is compatible with a digital control system. Another kind of transducer is now becoming available that encodes the value of the physical property into a signal that can be directly read by a digital control system. These devices are called resonant transducers. Resonant transducers are oscillators whose frequency depends in a known way on the physical property being measured. These devices output a train of rectangular pulses whose repetition rate encodes the value of the quantity being measured. The pulses can in most cases be fed directly into the 80C51BH, which then measures either the frequency or period of the incoming signal, basing the measurement on the accuracy of its own clock oscillator. The 80C51BH can even do this in its sleep; that is, in Idle. When the frequency or period measurement is completed, the C51BH wakes itself up for a very short time to perform a sanity check on the measurement and convert it in software to any scaling of the measured quantity that may be desired. The software conversion can include corrections for nonlinearities in the transducer's transfer function. Resolution is also controlled by software, and can even be dynamically varied to meet changing needs as a situation becomes more critical. For example, in a process controller you can increase your resolution (``fine tune'' the control, as it were) as the process approaches its target. The nominal reference frequency of the output signal from these devices is in the range of 20 Hz to 500 kHz, depending on the design. Transducers are available that have a full scale frequency shift 2 to 1. The transducer operates from a supply voltage range of 3V to 20V, which means it can operate from the same supply voltage as the 80C51BH. At 5V, the transducer draws less than 5 mA (Reference 7). It can normally be connected directly to one of the C51BH's port pins, as shown in Figure 22. FREQUENCY MEASUREMENTS Measuring a frequency means counting pulses for a known sample time. Two timer/counters can be used, one to mark off the sample time and one to count pulses. If the frequency being counted doesn't exceed 50 kHz or so, one may equally well connect the transducer signal to one of the external interrupt pins, and count pulses in software. That frees up one timer, with very little cost in CPU time. The count that is directly obtained is TxF, where T is the sample time and F is the frequency. The full scale 270068 - 21 Figure 20. UPDATELCD Routine Writes Two Digits to an LCD 18 AP-252 range is Tx(Fmax-Fmin). For n-bit resolution 1 LSB e Tx(Fmax-Fmin) 2n Therefore the sample time required for n-bit resolution is Te 2n Fmax-Fmin For example, 8-bit resolution in the measurement of a frequency that varies between 7 kHz and 9 kHz would require, according to this formula, a sample time of 128 ms. The maximum acceptable frequency count would be 128 ms c 9 kHz e 1152 counts. The minimum would be 896 counts. Subtracting 896 from each frequency count (or presetting the frequency counter to b 896 e 0FC80H) would allow the frequency to be reported on a scale of 0 to FF in hex digits. 270068 - 22 Figure 21a. Using an LCD Driver 270068 - 23 Figure 21b. UPDATELCD Routine Writes 4 Digits to an LCD Driver 19 AP-252 At this point the value of the frequency of the transducer signal, measured to 8 bit resolution, is contained in FREQUENCY. Note that the timer can be reloaded on the fly. Note too that the timer can be reloaded on the fly. Note too that for 8-bit resolution only the low byte of the frequency counter needs to be read, since the high byte is necessarily 0. However, one may want to test the high byte to ensure that it is zero, as a sanity check on the data. Both bytes, of course must be reloaded. PERIOD MEASUREMENTS 270068 - 24 Figure 22. Resonant Transducer Does Not Require an A/D Converter To implement the measurement, one timer is used to establish the sample time. The timer is preset to a value that causes it to roll over at the end of the sample time, generating an interrupt and waking the CPU from its Idle mode. The required preset value is the 2's complement negative of the sample time measured in machine cycles. The conversion from sample time to machine cycles is to multiply it by 1/12 the clock frequency. For example, if the clock frequency is 12 MHz, then a sample 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 roll over in 128 ms is b 128000 e FE0C00, in hex digits. Note that the preset value is 3 bytes wide whereas the timer is only 2 bytes wide. This means the timer must be 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 to code the third timer byte to count down instead of up. If the third timer byte counts down, its reload value is the 2's complement of what it would be for an up-counter. For example, if the 2's complement of the sample time is FE0C00, then the reload value for the third timer byte would be 02, instead of FE. The timer interrupt routine might then be: TIMER INTERRUPT ROUTINE: DNJZ THIRD TIMER BYTE,OUT MOV TL0,#0 MOV TH0,#0CH MOV THIRD TIMERBYTE,#2 MOV FREQUENCY,COUNTER LO ;Preset COUNTER to 1896: MOV COUNTER LO,#80H MOV COUNTER HI,#0FCH OUT: RETI 20 Measuring the period of the transducer signal means measuring the total elapsed time over a known number, N, of transducer pulses. The quantity that is directly measured is NT, where T is the period of the transducer signal in machine cycles. The relationship between T in machine cycles and the transducer frequency F in arbitrary frequency units is Te Fxtal c (1/12), F where Fxtal is the 80C51BH clock frequency, in the same units as F. The full scale range then is Nx (Tmax b Tmin). For n-bit resolution. 1 LSB e Ns(Tmax-Tmin) . 2n Therefore the number of periods over which the elapsed time should be measured is Ne 2n Tmax-Tmin However, N must also be an integer. It is logical to evaluate the above formula (don't forget Tmax and Tmin have to be in machine cycles) and select for N the next higher integer. This selection gives a period measurement that has somewhat more than n-bit resolution, but it can be scaled back if desired. For example, suppose we want 8-bit resolution in the measurement of the period of a signal whose frequency varies from 7.1 kHz to 9 kHz. If the clock frequency is 12 MHz, then Tmax is (12000 kHz/7.1 kHz) x (1/12) e 141 machine cycles. Tmin is 111 machine cycles. The required value for N, then, is 256/(141-111) e 8.53 periods, according to the formula. Using N e 9 periods 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 AP-252 scale these values back to a range of 0 to 255, giving precisely the 8-bit resolution desired. To implement the measurement, one timer is used to measure the elapsed time, NT. The transducer is connected to one of the external interrupt pins, and this interrupt is configured to the transition-activated mode. In the transition-activated mode every 1-to-0 transition in the transducer output will generate an interrupt. The interrupt routine counts transducer pulses, and when it gets to the predetermined N, it reads and clears the timer. For the specific example cited above, the interrupt routine might be: INTERRUPT RESPONSE: DJNZ N,OUT MOV N,#9 CLR EA CLR TR1 MOV NT LO,TL1 MOV NT HI,TH1 MOV TL1,#9 MOV TH1,#0 SETB TR1 SETB EA CALL LOOKUP TABLE OUT: RETI In this routine a pulse counter N is decremented from its preset value, 9, to zero. When the counter gets to zero it is reloaded to 9. Then all interrupts are blocked for a short time while the timer is read and cleared. The timer is stopped during the read and clear operations, so ``clearing'' it actually means presetting it to 9, to make up for the 9 machine cycles that are missed while the timer is stopped. The subroutine LOOKUPTABLE is used to scale the measurement back to the desired 8-bit resolution. It can also include built-in corrections for errors or nonlinearities in the transducer's transfer function. The subroutine uses the MOVC A, @ A a DPTR instruction to access the table, which contains 270 entries commencing at the 16-bit address referred to as TABLE. The subroutine must compute the address of the table entry that corresponds to the measured value of NT. This address is DPTR e TABL a NT b NTMIN, where NTMIN e 999, in this specific example. LOOKUP TABLE: PUSH PUSH MOV ADD MOV MOV ACC PSW A,#LOW(TABLE-NTMIN) A,NT LO DPL,A A,#HIGH(TABLE-NMTIN) ADDC MOV CLR MOVC MOV POP POP RET A,NT HI DPH,A A A,@A0DTPR PERIOD,A PSW ACC At this point the value of the period of the transducer signal, measured to 8 bit resolution, is contained in PERIOD. PULSE WIDTH MEASUREMENTS The 80C51BH timers have an operating mode which is particularly suited to pulse width measurements, and will be useful in these applications if the transducer signal has a fixed duty cycle. In this mode the timer is turned on by the on-chip circuitry in response to an input high at the external interrupt pin, and off by an input low, and it can do this while the 80C51BH is in Idle. (The ``GATE'' mode of timer operation is described in the Intel Microcontroller Handbook.) The external interrupt itself can be enabled, so the same 1-to-0 transition from the transducer that turns off the timer also generates an interrupt. The interrupt routine then reads and resets the timer. The advantage of this method is that the transducer signal has direct access to the timer gate, with the result that variations in interrupt response time have no effect on the measurement. Resonant transducers that are designed to fully exploit the GATE mode have an internal divide-by-N circuit that fixes the duty cycle at 50% and lowers the output frequency to the range of 250 to 500 Hz (to control RFI). The transfer function between transducer period and measurand is approximately linear, with known and repeatable error functions. HMOS/CHMOS Interchangeability The CHMOS version of the 8051 is architecturally identical with the HMOS version, but there are nevertheless some important differences between them which the designer should be aware of. In addition, some applications require interchangeability between HMOS and CHMOS parts. The differences that need to be considered are as follows: External Clock Drive: To drive the HMOS 8051 with an external clock signal, one normally grounds the XTAL1 pin and drives the XTAL2 pin. To drive the CHMOS 8051 with an external clock signal, one must drive the XTAL1 pin and leave the XTAL2 pin unconnected. The reason for the difference is that in the 21 AP-252 HMOS 8051, it is the XTAL2 pin that drives the internal clocking circuits, whereas in the CHMOS version it is the XTAL1 pin that drives the internal clocking circuits. There are several ways to design an external clock drive to work with both types. For low clock frequencies (below 6 MHz), the HMOS 8051 can be driven in the same way as the CHMOS version, namely, through XTAL1 with XTAL2 unconnected. Another way is to drive both XTAL1 and XTAL2; that is, drive XTAL1 and use and external inverter to derive from XTAL1 a signal with which to drive XTAL2. In either case, a 74HC or 74HCT circuit makes an excellent driver for XTAL1 and/or XTAL2, because neither the HMOS nor the CHMOS XTAL pins have TTL-like input logic levels. Unused Pins: Unused pins of Ports 1, 2 and 3 can be ignored in both HMOS and CHMOS designs. The internal pullups will put them into a defined state. Unused Port 0 pins in 8051 applications can be ignored, even if they're floating. But in 80C51BH applications, these pins should not be left afloat. They can be externally pulled up or down, or they can be internally pulled down by writing 0s to them. 8031/80C31BH designs may or may not need pullups on Port 0. Pullups aren't needed for program fetches, because in bus operations the pins are actively pulled high or low by either the 8031 or the external program memory. But they are needed for the CHMOS part if the Idle or Power Down mode is invoked, because in these modes Port 0 floats. Logic Levels: If VCC is between 4.5V and 5.5V, an input signal that meets the HMOS 8051's input logic levels will also meet the CHMOS 80C51BH's input logic levels (except for XTAL1/XTAL2 and RST). For the same VCC condition, the CHMOS device will reach or surpass the output logic levels of the HMOS device. The HMOS device will not necessarily reach the output logic levels of the CHMOS device. This is an important consideration if HMOS/CHMOS interchangeability must be maintained in an otherwise CMOS system. HMOS 8051 outputs that have internal pullups (Ports 1, 2, and 3) ``typically'' reach 4V or more if IOH is zero, but not fast enough to meet timing specs. Adding an external pullup resistor will ensure the logic level, but still not the timing, as shown in Figure 23. If timing is an issue, the best way to interface HMOS to CMOS is through a 74HCT circuit. Idle and Power Down: The Idle and Power Down modes exist only on the CHMOS devices, but if one 22 270068 - 25 Figure 23. 0-to-1 Transition Shows Unspec'd Delay (Dt) in HMOS to 74HC Logic wishes to preserve the capability of interchanging HMOS and CHMOS 8051s the software has to be designed so that the HMOS parts will respond in an acceptable manner when a CHMOS reduced power mode is invoked. For example, an instruction that invokes Power Down can be followed by a ``JMP $'': CLR ORL JMP EA PCON,#2 $ The CHMOS and HMOS parts will respond to this sequence of code differently. The CHMOS part, going into a normal CHMOS Power Down Mode, will stop fetching instructions until it gets a hardware reset. The HMOS part will go through the motions of executing the ORL instruction, and then fetch the JMP instruction. It will continue fetching and executing JMP $ until hardware reset. Maintaining HMOS/CHMOS 8051 interchangeability in response to Idle requires more planning. The HMOS part will not respond to the instruction that puts the CHMOS part into Idle, so that instruction needs to be followed by a software idle. This would be an idling loop which would be terminated by the same conditions that would terminate the CHMOS's hardware Idle. Then when the CHMOS device goes into Idle, the HMOS version executes the idling loop, until either a hardware reset or an enabled interrupt is received. Now if Idle is terminated by an interrupt, execution for the CHMOS device will proceed after RETI from the instruction following the one that invoked Idle. The instruction following the one that invoked Idle is the idling loop that was inserted for the HMOS device. At this point, both the HMOS and CHMOS devices must be able to fall through the loop to continue execution. AP-252 One way to achieve the desired effect is to define a ``fake'' Idle flag, and set it just before going into Idle. The instruction that invoked Idle is followed by a software idle: SETB ORL JB IDLE PCON,#1 IDLE,$ Now the interrupt that terminates the CHMOS's Idle must also break the software idle. It does so by clearing the ``Idle'' bit: ... CLR RETI IDLE Note too that the PCON register in the HMOS 8051 contains only one bit, SMOD, whereas the PCON register in CHMOS contains SMOD plus four other bits. Two of those other bits are general purpose flags. Maintaining HMOS/CHMOS interchangeability requires that these flags not be used. REFERENCES 1. Pawlowski, Moroyan, Alnether, ``Inside CMOS Technology,'' BYTE magazine, Sept., 1983. Available as Article Reprint AR-302. 2. Kokkonen, Pashley, ``Modular Approach to C-MOS Technology Tailors Process to Application,'' Electronics, May, 1984. Available as Article Reprint AR-332. 3. Williamson, T., Designing Microcontroller Systems for Electrically Noisy Environments, Intel Application Note AP-125, Feb. 1982. 4. Williamson, T., ``PC Layout Techniques for Minimizing Noise,'' Mini-Micro Southeast, Session 9, Jan., 1984. 5. Alnether, J., High Speed Memory System Design Using 2147H, Intel Application Note AP-74, March 1980. 6. Ott, H., ``Digital Circuit Grounding and Interconnection,'' Proceedings of the IEEE Symposium on Electromagnetic Compatibility, pp. 292 - 297, Aug. 1981. 7. Digital Sensors by Technar, Technar Inc., 205 North 2nd Ave., Arcadia, CA 91006. 23 INTEL CORPORATION, 2200 Mission College Blvd., Santa Clara, CA 95052; Tel. (408) 765-8080 INTEL CORPORATION (U.K.) Ltd., Swindon, United Kingdom; Tel. (0793) 696 000 INTEL JAPAN k.k., Ibaraki-ken; Tel. 029747-8511 Printed in U.S.A./xxxx/0296/B10M/xx xx