CHAPTER 3. Parallel ports, power supply and the clock oscillator – Designing Embedded Systems with PIC Microcontrollers, 2nd Edition

CHAPTER 3. Parallel ports, power supply and the clock oscillator
So far we have looked a little at the theory of microcontroller architecture and its implementation in PIC microcontrollers. This chapter now begins to move from that theory to the practice of small-scale hardware design.
As we have seen, the microcontroller core has internal data and address buses. In a way these are like motorways, or inter-state freeways, carrying large amounts of traffic in both directions to a variety of different destinations. The microcontroller needs to be provided with a way of allowing that data flow to connect with the outside world, so that it can read in external digital values or output other values. In other words, it needs the equivalent of motorway junctions, where data can leave (or enter) the bus at designated times and locations. In the microcontroller world these junctions have many forms, as there are many different ways in which data can be input or output. The most general purpose of these is the parallel input/output port. This is one of the microcontroller's most essential peripherals, and is the opening subject of this chapter.
Given a working car engine, two essentials that it needs to run are fuel and a stream of sparks from the plugs. A microcontroller has similar needs. Its fuel is the low-level electrical power supply that it requires and, instead of a flow of sparks, it needs a regular sequence of clock oscillator pulses. A study of these forms the second half of this chapter.
By putting together our background knowledge already gained, an ability to work with digital input/output, and an ability to design a power supply and clock oscillator, we will be in the happy position of being able to start to design real systems.
In this chapter you will learn about:
• Why we need parallel input/output.
• How simple logic circuits can be developed to give a flexible interface between the microcontroller data bus and the outside world – these are the parallel ports.
• How external devices can be connected to the parallel port.
• The parallel input/output available on the PIC 16F84A.
• The essential hardware features of the power supply and clock oscillator.
• The Microchip approach to power supply and oscillator, with the 16F84A.
• The hardware design of the electronic ping-pong game.

3.1. The main idea – parallel input/output

Almost any embedded system needs to transfer digital data between its CPU and the outside world. This transfer falls into a number of categories, which can be summarised as:
Direct user interface, including switches, keypads, light-emitting diodes (LEDs) and displays.
Input measurement information, from external sensors, possibly being acquired through an analog-to-digital converter.
Output control information, for example to motors or other actuators.
Bulk data transfer to or from other systems or subsystems, moving in serial or parallel form, for example sending serial data to an external memory.
With this plethora of data coming and going, it is likely we will need to have a variety of digital inputs and/or outputs. These are divided broadly into serial and parallel. In serial data transfer, the information is transferred one bit at a time. Only a single interconnection is used to carry the data itself, although other lines are usually included for synchronisation and control. In parallel data transfer, a set (for example, eight) of interconnections is used. Each of these can carry 1 bit, and each works in parallel with the others. Data can thus be transferred in groups of bits, for example in bytes. Parallel input/output (I/O) is the workhorse for all the basic data interchange of a microcontroller, including interfacing with switches, LEDs, displays and so on. A group of parallel I/O interconnections, appearing on the pins of the microcontroller, is called a ‘parallel port’.

3.2. The technical challenge of parallel input/output

Our immediate challenge is how to provide the required interface between the microcontroller data and address buses and the outside world. As suggested above, we start with the data bus, a multi-purpose data highway. How can we grab the data we want from the bus, and transfer it to the outside world, via the parallel port? Alternatively, how can we take external input data and introduce it onto the data bus, at the right time and place, so that it gets to the right place within the microcontroller? Finally, given a port that can do these things, how can we make it really flexible, so that it can be used for input, or output, or a mixture of both, and can transfer a combination of data with possibly very different end uses?

3.2.1. Building a parallel interface

It should be simple to create a set of output pins to create an ‘output’ port (Figure 3.1). Let us assign an address in the memory map to the port. Whenever that address is selected by an instruction in the program, it activates a line called ‘Port Select’. A further line, ‘’, indicates whether the CPU is undertaking a Read (line is high) or Write (line is low) operation. This is gated with the Port Select line. Each line of the data bus is connected to a bistable, and all of these are clocked by the Port Select line. Then the value of the data bus is latched into the bistable whenever the port memory location is addressed, in Write mode. The outputs of the bistables are made available for connection to the outside world.
Figure 3.1
Two bits of a possible digital output port
It is equally simple to create a set of input pins (Figure 3.2). All that is needed is a tristate buffer gate connected between an external pin and a line of the data bus. When the buffer is enabled, again by a logical combination of Port Select line and control, the logic value of the external pin is briefly connected to the data bus line, and can be read by the CPU. Note that in this design the external data is not latched by the port; it must be held at a stable value by the external source.
Figure 3.2
Two bits of a possible digital input port
These ideas are quite attractive, but the reality is that it is inflexible to limit an external pin of an IC to just one function, whether input or output. It would be much neater to combine somehow the two circuits used for input and output, and let the user decide in which direction he/she wants the data to move. The diagram of Figure 3.3 does just that. It shows a possible ‘pin driver’ circuit for one bit of a parallel port. It is easy to pick out in it the circuits of Figure 3.1 and Figure 3.2. What must be added, however, is a further flip-flop (‘Direction’), which is set to determine whether this microcontroller pin is to act as an input or output. The state of this flip-flop is set by the program. It controls the ‘Output buffer’, which is enabled when the port bit is in output mode.
Figure 3.3
A bi-directional port pin driver circuit
This circuit forms the basis for a very useful bi-directional input/output pin driver, and it is easy to find versions of it in many popular microcontrollers. Sets of I/O pins are grouped together to form a parallel I/O port. Each ‘Data’ flip-flop then forms one bit of a ‘Data’ SFR (Special Function register), and each ‘Direction’ flip-flop forms one bit of a ‘Direction’ SFR, as seen in Figure 3.3. Each SFR is memory mapped, with its own unique address. Derived from that address is its select line, which goes high when that location is addressed. ‘Port Select’ selects the Data SFR and ‘Direction Select’ selects the Direction SFR.
By writing to the Direction SFR the user can determine which bits are to be input and which are to be output. By writing to the Data SFR he/she can set the value of all Data flip-flops, whether that pin is actually set as an output or not. This value is transferred to the I/O pin through the buffer for those pins which are enabled as outputs. By reading from the Data SFR the program can acquire the logical value of the I/O pin. If the pin is set as output, this value is simply the value held by the Data flip-flop and asserted on the I/O pin through the Output buffer. If the pin is set as an input, then an external signal should be connected to the pin, and the controller will read its value.
Having established this basic design, it is possible to extend it further to add other features. We will see this when we look at some PIC microcontroller examples. One simple extension is already indicated in Figure 3.3, however. This is the ‘Alternate Input Function’ line, which allows an internal peripheral to share the I/O pin.

3.2.2. Port electrical characteristics

Logic gates are designed to interface easily with each other, and if we connect logic gates from just one family together then we usually don't need to worry about the electrical details of what is going on. If, however, we are connecting logic devices (in this case microcontroller port bits) to non-logic elements (like LEDs or switches) then we do need to understand the electrical characteristics of the logic. In particular, we need to understand their input and output characteristics.
The output of a logic gate can be visualised, or ‘modelled’, as in Figure 3.4 (a). Purists will recognise the limitations of this model, but for our purposes it will suffice. If the output is at Logic high (or ‘1’), then the internal switch is in the upper position. It is in the lower position for Logic 0. In either case, the output is modelled as a voltage source in series with a resistor (in circuit theory this is called a ‘Thevenin equivalent’ circuit). VLH is the logic high-output voltage, with an output resistance of RS(high). VLL is the logic low-output voltage, with an output resistance of RS(low).
Figure 3.4
Modelling a logic gate output. (a) Generalised model. (b) Model of Complementary Metal Oxide Semiconductor (CMOS) logic gate output
In the case of CMOS (Complementary Metal Oxide Semiconductor) the situation is quite simple, as VLH is equal to the supply voltage and VLL is equal to 0 V. This is illustrated in Figure 3.4 (b). Thus, if the supply voltage is 5 V, then Logic 0 and 1 will be 0 and 5 V respectively, if no current is being drawn from the gate output.
In practice, RS(high) and RS(low) are not constant, but depend to some extent on the current being sourced or sunk from the gate output. Therefore, manufacturers frequently publish graphical information on the output characteristics. We will see this shortly for the 16F84A.

3.2.3. Some special cases

We review now two special types of I/O characteristic, which will be important as we explore the 16F84A parallel ports.

Schmitt trigger inputs

A Schmitt trigger (Figure 3.5) is a certain type of logic gate input which is designed to ‘clean up’ a corrupted logic signal. It has two input thresholds, with the ‘positive-going’ higher than the ‘negative-going’. A signal starting from a low value has to pass the negative-going threshold (at which point nothing happens) and then cross the ‘positive-going’ threshold, at which point the output changes state. The output will not reverse until the input (now negative-going) has returned to the negative-going threshold. Thus, small fluctuations which recross a threshold just crossed do not cause any change in output.
Figure 3.5
Schmitt trigger characteristics. (a) Buffer with Schmitt trigger input. (b) Input/output characteristic

The ‘Open Drain’ output

The Open Drain output is a flexible style of output that can be adapted either as a standard logic output, as a direct drive for small loads, or used for a special logic function known as ‘Wired-OR’. The output itself is as illustrated in Figure 3.6 (a). A logic gate drives the gate of a MOSFET (Metal Oxide Semiconductor Field Effect Transistor), whose unconnected Drain terminal forms the output. When the MOSFET gate drive is high, the FET conducts and a logic zero is asserted at the terminal. When the gate is low the FET will not conduct and (with no other connection) the terminal will be at an undefined voltage. If a pull-up resistor is connected from the Drain to the supply voltage, then the output acts more or less as a normal logic output. Without the active pull-up of a normal logic output, however, its rise time will be a little sluggish and the amount of current it can source will be limited by the resistor value.
Figure 3.6
The Open Drain output and some applications. (a) An Open Drain output. (b) Open Drain output driving load resistor. (c) The Wired-OR connection
The Open Drain output can also be used to drive a simple load, acting as illustrated in Figure 3.6 (b). Usefully, the load does not have to be supplied from the same voltage as the logic supply, although it would have to be of the same polarity. Therefore, for example, a microcontroller supplied from 5 V (VS1 in the diagram) could drive a load supplied from 12 V (VS2 in the diagram), if all operating requirements are met.
Another important application of the Open Drain output is the ‘Wired-OR’ connection, shown in Figure 3.6 (c). Here several Open Drain outputs are connected together and tied high through a single pull-up resistor, RPU. If all outputs are off, then the common line (VO) is high. If any one output goes low, then the common line is pulled low. This is a possible way of achieving the OR or NOR logic function, and important for certain types of serial link, as we shall see later.

3.3. Connecting to the parallel port

3.3.1. Switches

Switches are extensively used in embedded systems. Our main initial interest is not to switch directly a voltage or current, but to convert the switch position to a logic level that can be read by a microcontroller port bit. Switches are used as a direct user interface in the form of push-buttons, toggle switches, slide switches, or as thumbwheel or rotary switches. They are also used, in the form of microswitches, to detect certain types of mechanical movement.
The simplest way of deriving a logic level from a switch is shown in Figure 3.7 (a). This shows a Single-Pole, Double-Throw (SPDT) switch, with one terminal connected to ground and the other to the supply. The switch wiper simply selects one of these two as the logic input. Some logic families advise against direct connection of a logic input to the supply voltage, so a series resistor (shown dotted) might be in order.
Figure 3.7
Connecting switches to logic inputs. (a) SPDT connection. (b) SPST with pull-up resistor. (c) SPST with pull-down resistor
There is a slight disadvantage to the connection of Figure 3.7 (a) as it requires the SPDT switch. A simpler option, using just a Single-Pole, Single-Throw (SPST) switch, for example a push-button, is shown in Figure 3.7 (b). Here a pull-up resistor is connected to one terminal of the switch, with the other terminal connected to ground. If the switch is closed, then the input to the logic gate, VI, is 0 V and a current VS/R flows to ground. If the switch is open then VO is equal to VS. To reduce wasted current when the switch is closed, the value of R should be high. If it is too high, however, then the Logic 1 level that it is meant to define may not be properly sustained. To evaluate the upper limit of the pull-up resistor, the input leakage current and logic thresholds need to be applied (as demonstrated in Chapter 2 of Ref. 1.1). For PIC microcontrollers, pull-up values in the range 10–100 kΩ are usually appropriate. The circuit of Figure 3.7 (b) is very useful and widely applied, as many simple switches (e.g. PCB (Printed Circuit Board) mounting slide switches and push-buttons) are only available as SPST.
The switch circuit of Figure 3.7 (b) can be reconnected as in Figure 3.7 (c). The characteristics of some logic families (for example, TTL (Transistor–Transistor Logic)) do, however, place restrictions on the use of this circuit, as the current sourced from the gate input significantly affects the action of the pull-down resistor. The circuit can be applied with PIC microcontrollers.

3.3.2. Light-emitting diodes

In certain semiconductor materials light is emitted as current flows across a forward-biased p–n junction. LEDs exploit this phenomenon. LEDs made of gallium arsenide (GaAs) emit light in the infrared, and if phosphorus is added in increasing proportions the light moves to visible red and ultimately to green. LEDs are widely available in red, green and yellow, as single devices, and as arrays, bargraphs and alphanumeric displays.
Because they are diodes, LEDs display the normal voltage–current relationship of a forward-biased diode. This means that, to a reasonable approximation, the voltage across an LED is constant if it is conducting. Note, however, that this forward voltage is considerably higher for GaAs than it is for silicon. Example LED characteristics, for red and green Kingbright LEDs, are shown in Figure 3.8. From these graphs it can be seen that the voltage across the red LED changes from 1.90 to 2.00 V if the current increases from 5 to 20 mA. For the green it changes from 1.95 to 2.20 V for the same current range. These voltage values are typical for all LEDs of similar type, with red having a slightly lower forward voltage compared to green or yellow.
Figure 3.8
Example Kingbright LED characteristics [Ref. 3.1]. (a) High-efficiency red. (b) Green.
Reproduced with permission of Kingbright Elec. Co. Ltd
The different colours do not give equal intensities for equal drive currents, as shown by the data in Figure 3.8. Red is the most efficient, which may account for its greater popularity. For a single LED to be comfortably visible, it typically requires around 10mA of current. Brighter ones may require up to 20 mA, but special low-power devices (such as the high-efficiency red) need as little as 1 or 2mA to be seen.
An LED can be driven from a logic output, for example a microcontroller port, as long as its current requirements can be met. Depending on the capabilities of the port output they can be connected so that the output is sourcing current (Figure 3.9 (a)) or sinking current (Figure 3.9 (b)).
Figure 3.9
Driving LEDs from logic gates. (a) Gate output sourcing current to LED. (b) Gate output sinking current from LED
CMOS logic families have symmetrical outputs and can source or sink almost equally well, so either of these circuits can be applied. In contrast, TTL logic can source little current but can sink a comparatively large amount, and therefore the configuration of Figure 3.9 (b) is preferred in this case.
A current-limiting resistor must normally be included in series with the LED. This is calculated as shown below by considering the voltages in the circuit. Precise values are not usually required.
An exception to the need for a series resistor, which must be cautiously applied, is when the logic is powered from a comparatively low voltage, and its internal output resistance itself forms an appropriate value for the current-limiting resistor.

3.4. The PIC 16F84A parallel ports

We saw in Chapter 2 that the 16F84A has two ports, A and B. A is 5-bit, while B is 8-bit. Notice from Figure 2.1 that some port bits have more than one function. We will see that the 16F84A adapts the generic pin driver circuit of Figure 3.3 and cleverly weaves in these extra functions.
The SFRs that relate to the ports are seen in Figure 2.5. In each case the port data itself appears in the PORTA or PORTB register (i.e. these act as the ‘Data’ SFR of Figure 3.3), while the data direction is determined by the bit values set in the TRISA or TRISB registers (i.e. these act as the ‘Direction’ SFR of Figure 3.3).
We will now explore the ports in further detail. Perhaps the most straightforward is Port B, with which we accordingly start.

3.4.1. 16F84A Port B

This is a general-purpose 8-bit bi-directional port, with a pin driver circuit similar to that in Figure 3.3. The simplest bits, 0 to 3, are illustrated in Figure 3.10 (a). The data latch can be seen in each circuit, while the ‘TRIS latch’ in Figure 3.10 replaces the ‘Direction’ latch of the earlier diagram. It can be seen that if the ‘TRIS latch’ output is set to 0, then the buffer that it drives is enabled and the port bit is in output mode.
Figure 3.10
Block diagram of Port B pin driver circuits. (a) Pins RB3 to RB0. (b) Pins RB7 to RB4 (supplementary labels in shaded boxes added by the author)
There are four enhancements to the simple pin driver circuit we saw earlier:
• The incoming data is latched, through the lowest latch in the diagram, rather than just its instantaneous value being read.
• The state of the ‘TRIS latch’ can be read via the buffer controlled by the RD TRIS line. It follows that the TRIS register acts as a normal read/write memory location, and the program can check if necessary the values previously stored there.
• Bit 0 is also the external interrupt input and has a Schmitt trigger interface.
• ‘Weak pull-up’ resistors can be switched on for all port bits used as inputs. These can be applied to replace the resistor in circuits like in Figure 3.7 (b). The pull-up is implemented with a p-channel MOSFET, seen at the top of the diagram. They are enabled for all port bits set as input by clearing the bit RBPU in the OPTION register. (This is seen memory-mapped in Figure 2.5 or in full in Figure 6.9.)
Bits 4 to 7 of Port B are seen in Figure 3.10 (b). They have a useful ‘interrupt on change’ facility. As with the lower-numbered bits, the data value is latched as input data is read. On these bits, however, the previous input value, from the last time the port was read, is retained on another latch. Its stored value is compared with the current input value. Any difference is detected by an Exclusive OR gate, whose output can generate an interrupt. This capability will be considered in detail in Chapter 6.

3.4.2. 16F84A Port A

Like Port B, this can be used as a general-purpose bi-directional digital port. The basic port pin driver (Figure 3.11 (a)) is very similar to the Port B pin. The diagram this time draws out in full the output tristate buffer. Bit 4 (Figure 3.11 (b)) doubles as the Timer 0 clock input. It also has a Schmitt trigger input characteristic and an Open Drain output, as described in Section 3.2.3. The full device data indicates that the absolute maximum permissible voltage applied to this Open Drain pin is 8.5 V. Therefore, the ability to drive an external load from a supply higher than the microcontroller itself can only be applied in a limited way.
Figure 3.11
Block diagram of Port A pin driver circuits. (a) Pins RA0, 1, 2 and 3. (b) Pin RA4/T0CKI (supplementary labels in shaded boxes added by the author)

3.4.3. Port output characteristics

The 16F84A port output characteristics are shown in Figure 3.12 for a supply voltage of 3.0 V. In Figure 3.12 (a) we see (at 25°C) how the output voltage for Logic 1 is 3 V when the output current is 0, but falls to around 1.7 V when the output current is 10 mA, flowing out of the gate. Similarly, in Figure 3.12 (b) we see (at 25°C) how the output voltage for Logic 0 is 0 V when the output current is 0, but rises to around 0.8 V when the output current is 22.5 mA (flowing into the gate). It is curves like these that can be used to find the VOL and VOH values used in (3.1) and (3.2) once a value for ID is known. Graphs are also given in the full data for characteristics with a 5 V supply.
Figure 3.12
16F84A port output characteristics. (a) VOh vs. IOH (VDD = 3 V, −40 to 125°C). (b) VOl vs. IOl (VDD = 3 V, −40 to 125°C) (dashed lines added by the author)
Another way of applying these curves is to deduce from them an approximate output resistance. This can be done by measuring the gradient of the curve at a particular point. A simple construction to do this has been added to each plot. By dividing vertical (voltage) by horizontal (current) for each of these, output resistances of approximately 130 Ω when at Logic high and 36 Ω when at Logic 0 can be deduced. If we call these two values ROH and ROL respectively, (3.1) and (3.2) can be written in a different form:

3.5. The clock oscillator

The choice of microcontroller clock source determines some of its fundamental operating characteristics. While ‘faster is better’ in terms of operating speed and program execution, faster is definitely worse in terms of power consumption, and also possibly in terms of electromagnetic interference. All timed elements within the microcontroller almost invariably depend on the clock characteristics. If stable and accurate timing is required, then the clock oscillator must be stable and accurate. With these points in mind, the clock source must be chosen with care and understanding. This section starts with a review of the clock technologies available, before moving on to looking at the options offered with the 16F84A.

3.5.1. Clock oscillator types

Broadly, there are two types of oscillator circuit in common use in microcontrollers, as illustrated in Figure 3.13. In the resistor–capacitor (RC) type (Figure 3.13 (a)), a capacitor is charged through a resistor from the supply rail. The capacitor voltage drives the input of a Schmitt trigger buffer. When the Schmitt trigger threshold is exceeded, its output goes high, switching on the MOSFET transistor to which it is connected. The capacitor is quickly discharged, the Schmitt output goes low, the MOSFET is switched off and the charging process starts again. This continues for as long as power is maintained. The clock signal is taken from the rectangular waveform generated at the Schmitt output. This simple circuit is integrated onto many larger ICs requiring a clock signal. Users are then usually required to connect resistor and capacitor externally, choosing these to set the desired frequency. It is important to note, however, that RC oscillators can be implemented entirely on-chip. They are very low-cost and produce a clock signal very reliably. As resistor, capacitor, power supply and Schmitt trigger threshold values all vary with temperature, their frequency is not very stable. They cannot therefore be used where precise timing is required.
Figure 3.13
Microcontroller oscillator generator circuits. (a) Resistor–capacitor (RC). (b) Crystal or ceramic
The crystal oscillator (Figure 3.13 (b)) depends on the piezo-electric properties of quartz crystal. Any mechanical distortion of the material causes a voltage to be produced across opposite sides of it; similarly, if a voltage is applied to the material, a mechanical distortion results. Crystals are carefully cut into very thin slices (usually discs), have tiny electrodes attached and are mounted so that they can vibrate. When connected in the feedback path across a logic inverter, as the figure shows, the crystal can be forced through piezo-electric action into mechanical vibration. This translates into electrical oscillation, an oscillation that is sustained by the action of the logic gate. Small-value capacitors connected from either side of the crystal to ground optimise the electrical conditions needed for this oscillation.
Crystal vibration occurs at a fixed and remarkably stable frequency – this is the great advantage of the crystal oscillator. The crystals themselves tend to be on the expensive side (although cost continues to fall) and mechanically fragile. An alternative is the ceramic resonator. This has similar piezo-electric properties to the crystal and is connected in an identical way. It is, however, both lower in cost and rather less stable in frequency. Crystals are the only option when precise timing functions, derived from the clock oscillator, are required.

3.5.2. Practical oscillator considerations

All microcontroller manufacturers go a long way towards making it easy to create a clock waveform for their microcontrollers. Usually, this is done by including the circuits of Figure 3.13, possibly in merged form, on-chip. One may be forgiven, therefore, for thinking that setting up the oscillator on a microcontroller is a straightforward thing – in fact it isn't, and unreliable or non-functioning oscillators are a cause of real frustration with novice builders. Oscillator frequency shows greater or lesser dependence on supply voltage, temperature, humidity, PCB layout and possibly other factors. Crystals in particular are sensitive to poor PCB layout. It is important to exclude parasitic resistance, capacitance or inductance by having very short PCB tracks, therefore locating the crystal close to the body of the microcontroller.

3.5.3. The 16F84A clock oscillator

The 16F84A can be configured to operate in four different oscillator modes, allowing implementation of RC, crystal or ceramic oscillators. These are detailed below. It can also accept an external clock source. The user selects which mode is to be used by setting bits in the Configuration Word (Figure 2.6).
XTcrystal. This is the standard crystal configuration. It is intended for crystals or resonators in the range 1–4 MHz.
HShigh speed. This is a higher drive version of the XT configuration. It recognises that higher-frequency crystals, and ceramic resonators in general, require a higher drive current. It is intended for crystal frequencies in the region of 4 MHz or greater, and/or ceramic resonators. It leads to the highest current consumption of all the oscillator modes.
LPlow power. This mode is intended for low-frequency crystal applications and gives the lowest power consumption possible. In many cases this will be 32.768 kHz (i.e. 215), which is the most popular frequency for low-power, time-sensitive applications, for example wristwatches. It will, however, operate at any frequency below around 200 kHz.
RCresistorcapacitor. For this an external resistor and capacitor must be connected to pin 16, replicating the circuit of Figure 3.13 (a). This is the lowest-cost way of getting an oscillator, but should not be used when any timing accuracy is required. The nominal frequency of oscillation can be predicted with limited accuracy only, and even then it will drift with changing temperature, supply voltage and time. An example of a use of the RC oscillator appears in the electronic ping-pong game case study at the end of this chapter.
As seen in Figure 3.1, the 16F84A has two oscillator pins, OSC1 (pin 16) and OSC2 (pin 15). Between these lies a logic inverter and associated circuitry. Figure 3.14 shows the possible oscillator configurations that can be connected using these pins. Either a crystal or a ceramic can be connected to create the oscillator circuit of Figure 3.14 (a). Any of the three speed ranges outlined above can be invoked through the Configuration Word. An RC oscillator can also be used, as shown in Figure 3.14 (b). The approximate oscillation frequency can be selected by consulting graphical information given in the ‘Electrical Characteristics’ section of the data sheet, for example as seen in Figure 3.15. Finally, an external clock source can simply be connected to the OSC1 pin (Figure 3.14 (c)). Further guidance on oscillator design for Microchip microcontrollers can be found in Ref. 3.2.
Figure 3.14
Ways of supplying a clock waveform to the 16F84A. (a) Crystal or ceramic, HS, XT or LP. (b) Resistor–capacitor. (c) Externally supplied clock
Figure 3.15
Average resistor–capacitor oscillator frequency vs. VDD for variable R, C = 100 pF, 25°C

3.6. Power supply

3.6.1. The need for power, and its sources

Like any electronic circuit, a microcontroller and the overall embedded system need to be supplied with electrical power. Traditionally, much logic circuitry is supplied at 5 V, arising from the voltage specified for the TTL family. With the growth in battery-powered equipment and developments in electronic technology, supply voltages have been pushed down, and 3.3 and 3.0 V supplies are now common.
Operating conditions for electronic components are specified in the manufacturer's data sheet. In terms of power supply there are two important issues: the supply voltage required and the current that the device will then take from the supply. This supply current will be dependent on operating frequency. Also given are ‘absolute maximum ratings’, which give voltage and power dissipation levels beyond which the device must not be taken.

3.6.2. 16F84A operating conditions

The essential operating conditions of the 16F84A are shown in Figure 3.16. From this it can be seen that a supply voltage of between 4.0 and 5.5 V is required, unless the HS oscillator mode is used. In this case the supply voltage must not be below 4.5 V. In ‘Sleep’ mode (when all program execution is suspended and the oscillator is switched off), the supply voltage can be dropped right down to 1.5 V and the data in RAM is still retained. If operation from lower supply voltages is required, then the 16LF84A should be used.
Figure 3.16
The 16F84A basic operating conditions
Looking further down the table, we see how much supply current depends on oscillator frequency. A typical supply current of 1.8 mA can be expected when running at 4 MHz with a supply voltage of 5.5 V. If the oscillator frequency is increased to 20 MHz, then the supply current rises to 10 mA. It's worth mentioning that both these values are actually very good, and compare well with many other, more power-hungry microcontrollers. If we want to operate at really low currents, however, then look what the 16LF84A offers at low frequency – a staggering 15 μA!
You may recognise that, for a battery-powered system, the required supply voltage of the 16F84A makes a three-cell alkaline battery supply a useful option. This gives a supply of around 4.5 V. Suppose you powered the system with three AA cells, each with a nominal capacity of 800 mAh. Running at 1.8 mA would give a battery life of 444 hours, or 18.5 days. Running at 10 mA would give 80 hours, or 3.3 days, while 15 μA consumption would lead to 53 333 hours, equivalent to 2222 days or just over six years! In this case battery self-discharge would potentially be significant. The above calculations of course only take account of the consumption of the microcontroller, and not of any other parts of the circuit.
An important opportunity for conserving power is through Sleep mode. This is introduced in Section 6.6 of Chapter 6.

3.7. The hardware design of the electronic ping-pong game

The electronic ping-pong game project was introduced in Chapter 1. Its circuit diagram can be seen in Appendix 2, Figure A2.1. We are now in a position to understand every detail of its circuit design, with the exception only of the programming connections, which appear top right of the diagram. These should be disregarded for now. Power is supplied from two AAA cells, which are connected to the VSS and VDD pins of the microcontroller via an on off switch. Because the power supply is only 3 V, an LF version of the microcontroller is used. A 100 nF decoupling capacitor across the power supply smooths voltage spikes which may be induced as a result of the action of the microcontroller internal circuitry. is simply tied to the supply rail, as no Reset function is needed for this simple game.
It can be seen that an RC oscillator is used. This is reasonable, as it is a cost-conscious application with no time-critical elements. Figure 3.15 shows that for the values used, and with a supply voltage of 3.0 V nominal, the oscillator frequency will be 800 kHz.
Let us now look at the use of the parallel ports. It can be seen that the two player paddles, connected to bits 3 and 4 of Port A, follow the pattern of Figure 3.7 (b), with 10-kΩ pull-up resistors. The score and out-of-play LEDs take up the remaining bits of Port A, and the ‘ball flight’ LEDs are all connected to Port B. All LEDs are high-efficiency types and are connected according to Figure 3.9 (a). Noting the approximate 130 Ω output resistance derived in Section 3.4.3 of this chapter, the total resistance in series with each LED is (560 + 130) Ω. With a forward voltage across the LED of around 1.8 V, the current is given by applying equation (3.3), i.e.
This current value is just adequate for this type of application and LED, where only close-up viewing is expected. It would in general be viewed as low.
We will be using the ping-pong hardware in the chapters which follow to develop a number of programs. It is helpful, though not essential, to have your own ping-pong hardware in order to run these. If you do this, you will also need access to a programming tool, as described in Chapter 4. The ping-pong hardware can be built at low cost by using a prototyping kit, or on stripboard or PCB. Check the book web site if you want to find a way of building your own.


• The parallel port allows ready exchange of digital data between the outside world and the controller CPU.
• It is important to understand the electrical characteristics of the parallel port and how they interact with external elements.
• While there is considerable diversity in the logic design of ports, they tend to follow similar patterns. The internal circuitry is worth understanding, as it leads to effective use of ports.
• The 16F84A has diverse and flexible parallel ports.
• A microcontroller needs a clock signal in order to operate. The characteristics of the clock oscillator determine speed of operation and timing stability, and strongly influence power consumption. Active elements of the oscillator are usually built in to a microcontroller, but the designer must select the oscillator type, and its frequency and configuration.
• A microcontroller needs a power supply in order to operate. The requirements need to be understood and must be met by a supply of the appropriate type.
3.1. Kingbright Elec. Co. Ltd. Taiwan;
3.2. Overview, Design Tips and Troubleshooting of the PICmicro Microcontroller Oscillator (2001). Microchip Technology Inc., Reference no. DS33023A;
Note: The first three questions provide useful insight into the workings of a port driver circuit. If you have a limited electronics background you may wish to skip them, or seek assistance from an instructor or colleague.
1. For the logic diagram of Figure 3.1, complete the timing diagram of Figure 3.17. The bus line indicated is either line of Figure 3.1 and the ext. pin is its corresponding input/output pin.
Figure 3.17
Timing diagram for Question 1
2. For the logic diagram of Figure 3.2, complete the timing diagram of Figure 3.18. The bus line indicated is either line of Figure 3.2 and the ext. pin is its corresponding input/output pin. The hatched area at the beginning of the bus line trace indicates here that the value cannot be determined from the information available. You will need to use this symbolism again later in the same trace.
Figure 3.18
Timing diagram for Question 2
3. For the logic diagram of Figure 3.3, complete the timing diagram of Figure 3.19. QDirn. is the Q output of the bistable labelled ‘Direction’, and QData is the Q output of the bistable labelled ‘Data’.
Figure 3.19
Timing diagram for Question 3
4. A CMOS port output is modelled as shown in Figure 3.4 (b). It is powered from 5V. The value of RS(high) is estimated to be 120 Ω and the value of RS(low) 70 Ω. One port pin will light an LED when it is at Logic 1, and another will light an LED when it is at Logic 0. An LED current of 4 mA is required; for this the LEDs have a forward voltage of 1.8 V. Sketch a circuit showing how each LED is connected and calculate appropriate resistor values.
5. Looking at the ping-pong circuit diagram in Figure A2.1, determine what words should be placed in each of TRISA and TRISB in order for each port bit to act correctly as input or output.
6. A push-button switch is connected to a microcontroller port input, using an external pull-up resistor. The supply voltage is 3.3 V.
(a) Sketch the circuit of this arrangement.
(b) As it is a power-conscious application, the current drawn when the switch is closed should not be more than 20 μA. What is the minimum pull-up resistor value?
(c) The port input is known to have a worst-case input leakage current of 5 μA, flowing into the input. What is the actual input voltage for the resistor value calculated above when the switch is not pressed?
7. Four Port B bits of a 16LF84A are used as outputs; two will drive green LEDs and two will drive red. Kingbright LEDs are to be used, with characteristics as shown in Figure 3.8. The red LEDs are to be lit with a current of 5 mA when the associated port bit is at Logic 1. The green are to be lit with a current of 12 mA when the bit is at Logic 0. The power supply is 3 V. Calculate the values of the series resistors needed. Is there a reason why the green LEDs are lit with a Logic 0 output?
8. Propose which oscillator type should be chosen for each of the 16F84A-based applications listed below, giving reasons.
(a) Scientific instrument control system, requiring intensive calculations and precisely timed outputs.
(b) Low-cost toy, timing not of high significance.
(c) Hand-held, battery-powered stopwatch.
(d) Human interface controller for mains-powered studio mixing desk; some precise timing required, but speed requirements modest.
9. Draw a complete design for the hardware of a hand-held electronic die, based on a PIC 16F84A. The output should be 7 LEDs, in the pattern shown in Figure 3.20. There should be one push-button to initiate a die ‘roll’, and an on–off slide switch. Do not include any programming interconnection.
Figure 3.20
LED pattern for electronic device