Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

PICmicro MCU: Interfacing External Devices - Power, Logic, LEDs, Analog I/O, Interrupts - , Exams of Microprocessors

An in-depth exploration of interfacing external devices with the picmicro mcu, covering topics such as power consumption estimation, digital logic levels, led handling, switch bounce, matrix keypads, lcds, and analog i/o. It also delves into the use of interrupts for efficient handling of external events.

Typology: Exams

Pre 2010

Uploaded on 08/18/2009

koofers-user-ab9-1
koofers-user-ab9-1 🇺🇸

10 documents

1 / 64

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
6
PICmicro®MCU
APPLICATION DESIGN
AND HARDWARE INTERFACING
After reading the previous two chapters and “Introduction to Electronics” on the CD-
ROM, you must feel like there is nothing left to understand about designing PICmicro®
MCU applications. In these chapters on the CD-ROM I have provided background on how
microcontroller interfacing is carried out and some of the theories and pitfalls that you
should be aware of. This chapter covers some specifics about how the PICmicro®MCU
works when wired to different interfaces.
CONTENTS AT A GLANCE
Estimating Application Power
Requirements
Reset
Interfacing to External Devices
DIGITAL LOGIC
DIFFERENT LOGIC LEVELS WITH ECL
AND LEVEL SHIFTING
LEDs
Switch Bounce
Matrix Keypads
LCDs
Analog I/O
POTENTIOMETERS
PULSE-WIDTH MODULATION (PWM) I/O
AUDIO OUTPUT
Relays and Solenoids
DC and Stepper Motors
R/C Servo Control
Serial Interfaces
SYNCHRONOUS
ASYNCHRONOUS (NRZ) SERIAL
DALLAS SEMICONDUCTOR 1-WIRE
INTERFACE
253
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40

Partial preview of the text

Download PICmicro MCU: Interfacing External Devices - Power, Logic, LEDs, Analog I/O, Interrupts - and more Exams Microprocessors in PDF only on Docsity!

PICmicro

MCU

APPLICATION DESIGN

AND HARDWARE INTERFACING

After reading the previous two chapters and “Introduction to Electronics” on the CD-

ROM, you must feel like there is nothing left to understand about designing PICmicro® MCU applications. In these chapters on the CD-ROM I have provided background on how microcontroller interfacing is carried out and some of the theories and pitfalls that you should be aware of. This chapter covers some specifics about how the PICmicro® MCU works when wired to different interfaces.

CONTENTS AT A GLANCE

Estimating Application Power

Requirements

Reset

Interfacing to External Devices

DIGITAL LOGIC DIFFERENT LOGIC LEVELS WITH ECL AND LEVEL SHIFTING

LEDs

Switch Bounce

Matrix Keypads

LCDs

Analog I/O

POTENTIOMETERS PULSE-WIDTH MODULATION (PWM) I/O AUDIO OUTPUT

Relays and Solenoids

DC and Stepper Motors

R/C Servo Control

Serial Interfaces

SYNCHRONOUS ASYNCHRONOUS (NRZ) SERIAL DALLAS SEMICONDUCTOR 1-WIRE INTERFACE

253

I am not trying to say that the PICmicro® MCU is a difficult microcontroller to interface to. Actually, it is one of the easiest eight-bit microcontrollers to develop interface applica- tions for. In different versions, with built-in oscillators and reset circuits, interfaces can be unbelievably easy to implement. Despite this, you should be aware of a few things that will help you make your applications more efficient and keep you from having difficult to de- bug problems.

Estimating Application

Power Requirements

Accurate power estimating for your applications is important because the expected power consumption affects how much heat is produced by the circuit and what kind of power supply is required by it. Although the PICmicro® MCU power can usually only be esti- mated to an order of a magnitude, this is usually good enough to ensure that the circuit won’t overheat, the power supply won’t burn out or the batteries will not be exhausted be- fore the required execution time has passed. For the PICmicro® MCU itself, the “intrinsic” current, what I call the current consumed by the microcontroller with nothing connected to it, is available from Microchip in the data sheets. For the PIC16F87x, rated at 4 MHz, Table 6-1 lists the IDD (the supply current or intrinsic current), according to the oscillator type. The current rating for the oscillator type selected in the configuration fuses should be the basis for your estimate. Notice that as the clock frequency changes, the intrinsic cur- rent consumption will go up at a rate of about one mA per MHz. For estimating purposes, I recommend that you use the worst case for the oscillator selected. Next, select the current requirements for the devices that connect directly to the PICmi- cro® MCU. Depending on their operation, the current requirements can change drasti- cally. For example, an LED that is off consumes just no current, and one that is on can consume from five to 20 mA. Again, for these devices, the worst cases should be used with the estimate. Also, note that different devices will respond differently, depending on how they are used. A very good example of this is a LCD display. Many modern LCDs have built-in pull-ups to make interfacing easier for electronic devices that have open collector outputs (such as the 8051). Typically, these devices current requirements will be quoted with the

254 PICmicro® MCU APPLICATION DESIGN AND HARDWARE INTERFACING

TABLE 6–1 PICmicro® MCU Oscillator Current Consumption Comparison

OSCILLATOR IDD FREQUENCY

LP 52.5 A 32 kHz RC 5 mA 4 MHz XT 5 mA 4 MHz HS 13.5 mA 4 MHz

MCU’s clock to stabilize before the application starts. In the low-end and high-end PICmi- cro® MCU’s, this function is not always available. PWRTE does not have to be enabled if a stable clock is being input to the PICmicro® MCU, such as in the case where a “canned oscillator” is used as the PICmicro® MCU’s clock source instead of a crystal, ceramic resonator, or RC network. When the _MCLR pin is made active (pulled low), the oscillator stops until the pin is brought back high. As well, the oscillator is also stopped during sleep mode to minimize power consumption. The PWRTE 72 ms delay is required in these cases, as well to ensure the clock is stable before the application’s code starts executing. If the PICmicro® MCU is run at low voltage (less than 4.0 volts), do not enable the built-in Brown-Out Reset (BOR), unless it is available with a low-voltage selector option. Once power drops below 4.0 volts, then circuit will become active and will hold the PICmicro® MCU reset—even though it is receiving a valid voltage for the application. The low-voltage option usually means that the brown-out reset will reset the PICmicro® MCU when the input voltage is below 4.0 volts or 1.8 volts. If you are going to use low voltage and want a brown-out detect function, this can be added with a Zener diode and a comparator as is shown in Fig. 6-2. In this circuit, voltage is reduced by the Zener diode voltage regulator to 3 volts. If Vcc goes below three volts, this circuit will put the PICmicro® MCU into reset. The voltage- divider values can be changed for different ratios and R can be quite high (100 K) to minimize current drain in a battery-driven application. The PIC12C5xx and 16C505 PICmicro® MCU’s can provide an internal reset function, which uses Vdd as the _MCLR pin input. This frees the _MCLR pin for use as an input. The freed _MCLR pins generally cannot be used as an output. A common use for this pin is RS-232 input using a resistor as a current limiter and pro- viding bit-banging software to read the incoming values. If you use the _MCLR/I/O pin in this fashion, be sure that you “clamp” the pin shown in Fig. 6-3. If the incoming negative voltage is not clamped within the PICmicro® MCU, the nega- tive voltage could cause the PICmicro® MCU to be forced into reset mode. If the positive voltage is not clamped, then the PICmicro® MCU could go into the programming mode. The general-purpose pins are designed with clamping diodes built in and will not allow in- puts to be driven outside Vdd or ground. Not clamping the input pins can cause some con- fusing problems when you first work with the PICmicro® MCU in this type of application. The use of clamping diodes for RS-232 interfacing is shown in the “Serial LCD Interface” in Chapter 16.

256 PICmicro® MCU APPLICATION DESIGN AND HARDWARE INTERFACING

PICmicro® MCU reset with “brown out” protection

Figure 6-

Interfacing to External Devices

The previous chapters have provided a lot of information about the peripheral hardware built into the PICmicro® MCU that will help making applications easier. Coupled with the information contained in the appendices, you would have thought I had it all covered. The following sections cover some of the hints and tips I’ve learned over the years for interfacing PICmicro® MCUs to other devices. With this information, I have also in- cluded source code for the different interface hardware. This code is available on the CD- ROM as snippets that can be cut and pasted into your applications, as well as into macros that can be added to the applications. Much of this information and code is used later in the book when I go through the ex- periments and projects. Some of the interfaces will seem very complex or difficult to cre- ate, but I have tried to work through many of the difficulties and provide you with sample circuits that are simple and cheap to implement.

DIGITAL LOGIC

It should not be surprising that the PICmicro® MCU can interface directly to TTL and CMOS digital logic devices. The PICmicro® MCU’s parallel I/O pins provide digital out- put levels that can be detected properly by both logic technologies and inputs that can de- tect logic levels output from these logic families. If you check the PICmicro® MCU data sheets, you will see that the output characteris- tics are:

Vol (output low voltage)  0.6 V (max.) Voh (output high voltage)  Vdd  0.7 V (min.) This specification is given to allow for different Vdd power inputs. For a Vdd of 5 volts, you can expect a “high” output of 4.3 volts or greater (normally, I see 4.7 volts when a PICmicro® MCU pin is not under load). If the power voltage input ( Vdd ) was reduced to 2 volts, low output would still be 0.6 volts and high output becomes 1.3 volts ( Vdd – 0.7) or greater. The PICmicro® MCU pins are specified to drive (source) up to 20 mA and sink (pull the output to ground) 25 mA. These current capabilities easily allow the PICmicro® MCU to drive LEDs. The total current sourced or sunk by the PICmicro® MCU should not ex- ceed 150 mA (which is six I/O pins sinking the maximum current).

INTERFACING TO EXTERNAL DEVICES 257

Internal reset allow- ing “_MCLR” pin to be used for RS- 232 input

Figure 6-

bsf STATUS, RPO ; Put PORTB into Input Mode movlw 0x0FF movwf TRISB ∧^ 0X bcf STATUS, RPO bcf PORTA, 0 ; Drop the “_RD” line call Dlay ; Delay until Data Output Valid movf PORT B, w ; Read Data from the Port bsf PORT A, 0 ; “_RD”  1 (disable “_RD” Line)

Writing to one of the output registers is similar:

bsf STATUS, RPO clrf TRIS B ∧^ 0X080 ; PORTB Output bcf STATUS, RPO bcf PORTA, 1 ; Enable the “_WR1” Line movwf PORTB ; output the Data call Dlay ; Wait Data Receive Valid bsf PORTA, 1 ; “_WR1”  1.

Combining input and output Often when working on applications, you will find some situations where peripheral devices will use more than one pin for I/O. Another case would be when you are connecting two devices, one input and one output and would like to combine them somehow so that you can reduce the number of PICmicro® MCU pins required. Fewer PICmicro® MCU pins means that you can use cheaper PICmicro® MCUs and avoid complex application wiring. This section presents two techniques for doing this and the rules governing their use. This might at first appear problematic and asking for problems with bus contention, but they really do work and can greatly simplify your ap- plication. When interfacing the PICmicro® MCU to a driver and receiver (such as a memory with a separate output and input), a resistor can be used to avoid bus contention at any of the pins (Fig. 6-5). In this situation, when the PICmicro® MCU’s I/O pin is driving out, it will be driving the Data In pin register and regardless of the output of the Data Out pin. If the PICmicro® MCU and Data Out pins are driving different logic levels, the resister will limit the current flowing between the PICmicro® MCU and the memory Data Out pin. The value received on the Data In pin will always be the PICmicro® MCU’s output due to the voltage drop within the registor.

INTERFACING TO EXTERNAL DEVICES 259

Figure 6-4 PICmicro® MCU simulated parallel 10 port

When the PICmicro® MCU is receiving data from the memory, its I/O pin will be put in input mode and the Data Out pin will drive its value to not only the PICmicro® MCU’s I/O pin, but the Data In pin as well. In this situation, the Data In pin should not be latching any Data In. To avoid this, in most cases where this circuit combines input and output, the two input and output pins are on the same device and the data mode is controlled by the PICmicro® MCU to prevent invalid data from being input into the device. This is an im- portant point because it defines how this trick should be used. The I/O pins that the PICmi- cro® MCU are connected to must be mutually exclusive and can never be transmitting data at the same time. A common use for this method of connection data in and data out pins is used in SPI memories, which have separate data input and output pins. The second trick is to have button input, along with an external device receiver. As is shown in Fig. 6-6, a button can be put on the same “net” as an input device and the PICmi- cro® MCU pin that drives it. When the button is open or closed, the PICmicro® MCU can drive data to the input device, the 100-K and 10-K resistors will limit the current flow between V (^) cc and ground. If the PICmicro® MCU is going to read the button high (switch open) or low (switch closed) will be driven on the bus at low currents when the pin is in input mode. If the button switch is open, then the 100-K resistor acts like a pull up and a 1 is returned. When the button switch is closed, then there will be approximately 0.5 volt across the 10-K resistor, which will be read as a 0. The button with the two resistors pulling up and down are like a low-current driver and the voltage produced by them is easily “overpowered” by active drivers. Like the first method, the external input device cannot receive data except when the PICmicro® MCU is driving the circuit. A separate clock or enable should be used to ensure that input data is received when the PICmicro® MCU is driving the line. Two points about this method; this can be extrapolated to work with a switch matrix keyboard. The circuit can become very complex, but it will work. Secondly, a

260 PICmicro® MCU APPLICATION DESIGN AND HARDWARE INTERFACING

Figure 6-5 PICmicro® MCU simulated parallel 10 port

Figure 6-6 Combining button in-put with digital I/O

I/O pin value will be changed at five cycles. I did this because this function is often used with I2C or other network protocols and using the carry flag allows bits to be shifted through this code easily. In the sample open-drain simulation code, I reset the specified pin before potentially changing its TRIS value. This is to prevent it from being the wrong value, based on reads and writes of other I/O pins. This is the “inadvertent pin changes” that I’ve written about elsewhere in the book.

DIFFERENT LOGIC LEVELS WITH ECL

AND LEVEL SHIFTING

Often, when working with PICmicro® MCUs and other microcontrollers, you will have to interface devices of different logic families together. For standard positive voltage logic families (i.e., TTL to CMOS), this is not a problem; the devices can be connected directly. But, interfacing a negative voltage logic to a positive voltage logic family (i.e., ECL to CMOS) can cause some problems. Although chips usually are available to provide this interface function (for both input and output), they typically only work in only one direction (which precludes bi-directional busses—even if the logic family allows it) and the chips can add a significant cost to the application. The most typical method of providing level conversion is to match the switching thresh- old voltage levels of the two logic families. As shown in Fig. 6-8, the ground level for the COMS microcontroller has been shifted below ground (the microcontroller’s “ground” is actually the CMOS 0 level). The purpose of this is to place the point where the microcontroller’s input logic switches between a 0 and a 1 (known as the input logic threshold voltage ) is the same as the ECL Logic. The re- sistor (which is between 1 K and 10 K) is used to limit the current flow because of the dif- ferent logic swings of the two different families. Looking at the circuit block diagram, you’re probably thinking that the cost of shifting the microcontroller power supply is much greater than just a few interface chips. Actually, this isn’t a big concern because of the low power requirements of modern CMOS microcontrollers. In Fig. 6-8, the microcontroller’s ground reference can be pro- duced by placing a silicon diode (which has a 0.7 voltage drop across it) between it and the ECL’s 2-volt power supply negative output. The 5-volt and 2-volt supplies’ positive out- put have a common “threshold” voltage for this circuit and the registor limits the CMOS

262 PICmicro® MCU APPLICATION DESIGN AND HARDWARE INTERFACING

Figure 6-8 ECL to CMOS logic level conversion

logic swing to the 1 volt ECL swing. This example might seem simplistic, but it would provide the ability to connect a CMOS 0- to 5-volt microcontroller to ECL logic (and al- low signals to be sent in either direction, between the PICmicro® MCU and the ECL Logic) at a very low cost.

LEDs

The most common form of output from a microcontroller is the Light-Emitting Diode (LED). As an output device, it is cheap and easy to wire to a microcontroller. Generally, LEDs require anywhere from 5 mA of current to light (which is within the output sink/source specification for most microcontrollers). But, what has to be remembered is, LEDs are diodes, which means that current flows in one direction only. The typical circuit that I use to control an LED from a PICmicro® MCU I/O pin is shown in Fig. 6-9. With this circuit, the LED will light when the microcontroller’s output pin is set to 0 (ground potential). When the pin is set to input or outputs a 1, the LED will be turned off. The 220 Ohm resistor is used for current limiting and will prevent excessive current that can damage the microcontroller, LED and the power supply. Elsewhere in the book, I have shown how this resistor value is calculated. Some microcontrollers (such as the PICmi- cro® MCU) already have current-limiting output pins, which lessens the need for the cur- rent-limiting resistor. But, I prefer to always put in the resistor to guarantee that a short (either to ground or Vcc ) cannot ever damage the microcontroller of the circuit it’s con- nected to (including the power supply). Probably the easiest way to output numeric (both decimal and hex) data is via seven- segment LED displays. These displays were very popular in the 1970s (if you’re old enough, your first digital watch probably had seven-segment LED displays), but have been largely replaced by LCDs. Seven-segment LED displays (Fig. 6-10) are still useful devices that can be added to a circuit without a lot of software effort. By turning on specific LEDs (each of which light up a segment in the display), the display can be used to output decimal numbers. Each one of the LEDs in the display is given an identifier and a single pin of the LED is brought out of the package. The other LED pins are connected together and wired to a common pin. This common LED pin is used to identify the type of seven-segment display (as either common cathode or common anode). Wiring one display to a microcontroller is quite easy—it is typically wired as seven (or eight, if the decimal point, DP, is used) LEDs wired to individual pins. The most important piece of work you’ll do when setting up seven-segment LED dis- plays is matching and documenting the microcontroller bits to the LEDs. Spending a few moments at the start of a project will simplify wiring and debugging the display later.

LEDs 263

Figure 6-9 LED connection to a microcontroller

to cycle the interrupt handler (i.e., eight seven-segment displays must cycle at least 400 digits per second, which is eight times as fast as a single display). You might feel that assigning a microcontroller bit to select each display LED to be somewhat wasteful (at least I do). I have used high-current TTL demultiplexer (i.e., 74S138) outputs as the cathode path to ground (instead of discrete transistors). When the output is selected from the demultiplexer, it goes low, allowing current to flow through the LEDs of that display (and turning it on). This actually simplifies the wiring of the fi- nal application as well. The only issue is to ensure that the demultiplexer output can sink the maximum of 140 mA of current that will come through the common cathode con- nection. Along with seven-segment displays, 14- and 16-segment LED displays are available, which can be used to display alphanumeric characters (A to Z and 0 to 9). By following the same rules as used when wiring up a seven-segment display, you shouldn’t have any prob- lems wiring the display to a PICmicro® MCU. Chapter 16 shows how seven- and 16-seg- ment LEDs can be used to display letters and numbers.

Switch Bounce

When a button is opened or closed, we perceive that it is a clean operation that really looks like a step function. In reality, the contacts of a switch bounce when they make contact, re- sulting in a jagged signal (Fig. 6-12). When this signal is passed to a PICmicro® MCU, the microcontroller can recognize this as multiple button presses, which will cause the application software to act as if multiple, very fast button presses have occurred. To avoid this problem the “noisy” switch press is “debounced” into an idealized “press,” or the step function (Fig. 6-13). Two common methods are used to debounce button inputs. The first is to poll the switch line at short intervals until the switch line stays at the same level for an extended period of time. A button is normally considered to be debounced if it

SWITCH BOUNCE 265

Figure 6-12 Oscilloscope picture of a switch “bounce”

does not change state for 20 ms or longer. By polling the line every 5 ms, this debouncing method can be conceptualized quite easily (Fig. 6-14). The advantage of this method is that it can be done in an interrupt handler and the line can be scanned periodically with a flag set if the line is high and another flag in the line is low. For the “indeterminate” stage, neither bit would be set. This method of debouncing is good for debouncing keyboard inputs. The second method is to continually poll the line and wait for 20 ms to go by without the line changing state. The algorithm that I use for this function is: ButLoop: while (Button  High); // Poll Until Button is Pressed for (Dlay  0; (Dlay  20msec) and (Button  Low); Dlay); if (Dlay ! 20 msec) // Repeat Process if 20 msecs have goto ButLoop; // Not gone by with Button Pressed This code will wait for the button to be pressed and then poll it continuously until either 20 ms has passed or the switch has gone high again. If the switch goes high, the process is repeated until it is held low for 20 ms. This method is well suited to applications that don’t have interrupts, only have one but- ton input, and have no need for processing while polling the button. As restrictive as it sounds, many applications fit these criteria. This method can also be used with interrupt inputs along with TMR0 in the PICmicro® MCU, which eliminates these restrictions. The interrupt handler behaves like the follow- ing pseudo-code when one of the port changes on interrupt bits is used for the button input: interrupt ButtonDebounce() // Set Flags According to the { // Debounced State of the Button

if (T0IF  1) { // TMR0 Overflow, Button Debounced T0IF  0; T0IE  0; // Reset and Turn off TMR0 Interrupts if (Button  High) { Pressed  0; NotPressed  0; // Set the State of the Button } else { Pressed  1; NotPressed  0;

266 PICmicro® MCU APPLICATION DESIGN AND HARDWARE INTERFACING

Figure 6-14 Polling to eliminate “bounce”

Figure 6-13 Idealized switch operation

atively small number of PICmicro® MCU pins. The PICmicro® MCU is well designed for simply implementing switch matrix keypads, which, like LCD displays that are ex- plained in the next section, can add a lot to your application with a very small investment in hardware and software. A switch matrix is simply a two-dimensional matrix of wires, with switches at each ver- tex. The switch is used to interconnect rows and columns in the matrix (Fig. 6-16). This diagram might not look like the simple button, but it will become more familiar when I add switchable ground connections on the columns (Fig. 6-17). In this case, by connecting one of the columns to ground, if a switch is closed, the pull down on the row will connect the line to ground. When the row is polled by an I/O pin, a 0 or low voltage will be returned instead of a 1 (which is what will be returned if the switch in the row that is connected to the ground is open). As stated, the PICmicro® MCU is well suited to implement switch matrix keyboards with PORTB’s internal pull-ups and the ability of the I/O ports to simulate the open-drain pull-downs of the columns (Fig. 6-18). Normally, the pins connected to the columns are left in tristate (input) mode. When a column is being scanned, the column pin is output en- abled driving a 0 and the four input bits are scanned to see if any are pulled low. In this case, the keyboard can be scanned for any closed switches (buttons pressed) us- ing the code:

int KeyScan() // Scan the Keyboard and Return when a { // key is pressed

int i  0; int key  1;

while (key  1) {

for (i  0; (i  4) & ((PORTB & 0x00F)  0x0F0); i);

268 PICmicro® MCU APPLICATION DESIGN AND HARDWARE INTERFACING

Figure 6-16 2x2 switch matrix

Figure 6-17 Switch matrix with pull down transistors

switch (PORTB & 0x00F) { // Find Key that is Pressed case 0x00E: // Row 0 key  i; break; case 0x00D: // Row case 0x00C: key  0x04  i; break; case 0x00B: // Row case 0x00A: case 0x009: case 0x008: key  0x08  i; break; else // Row key  0x0C  i; break; }//end switch }// end while

return key;

} // End KeyScan

The KeyScan function will only return when a key has been pressed. This routine will not allow keys to be debounced or for other code to execute while it is running. These issues can be resolved by putting the key scan into an interrupt handler, which ex- ecutes every 5 ms:

Interrupt KeyScan( ) // 5 msec Interval Keyboard Scan {

int i  0; int key   1

for (i  0; (i 4) & ((PORTB & 0x00F)  0x00F)); i); if (PORTB & 0x00F)!  0x00F) { // Key Pressed switch (PORTB & 0x00F) { // Find Key that is Pressed case 0x00E: // Row 0 key  i;

MATRIX KEYPADS 269

Figure 6-18 4x4 switch matrix connected to PORTB

LCDs

LCDs can add a lot to your application in terms of providing a useful interface for the user, debugging an application, or just giving it a professional look. The most common type of LCD controller is the Hitachi 44780, which provides a relatively simple interface between a processor and an LCD. Using this interface is often not attempted by new designers and programmers because it is difficult to find good documentation on the interface, initializ- ing the interface can be a problem, and the displays themselves are expensive. I have worked with Hitachi 44780-based LCDs for a while now and I don’t believe any of these perceptions. LCDs can be added quite easily to an application and use as few as three digital output pins for control. As for cost, LCDs can be often pulled out of old de- vices or found in surplus stores for less than a dollar. The purpose of this section is to give a brief tutorial on how to interface with Hitachi 44780-based LCDs. I have tried to provide all of the data necessary for successfully adding LCDs to your application. In the book, I use Hitachi 44780-based LCDs for a num- ber of different projects. The most common connector used for the 44780-based LCDs is 14 pins in a row, with pin centers 0.100” apart. The pins are wired as in Table 6-2. As you would probably guess from this description, the interface is a parallel bus, al- lowing simple and fast reading/writing of data to and from the LCD. The waveform shown in Fig. 6-19 will write an ASCII byte out to the LCD’s screen. The ASCII code to be displayed is eight bits long and is sent to the LCD either four or eight bits at a time. If four-bit mode is used, two nybbles of data (sent high four bits and then low four bits with an E clock pulse with each nybble) are sent to make up a full eight-bit trans- fer. The E clock is used to initiate the data transfer within the LCD. Sending parallel data as either four or eight bits are the two primary modes of operation. Although there are secondary considerations and modes, deciding how to send the data to the LCD is the most crucial decision to be made for an LCD interface application.

LCDs 271

TABLE 6–2 Hitachi 44780 Based LCD Pinout

PIN DESCRIPTION

1 Ground 2 Vcc 3 Contrast Voltage 4 “R/S” - Instruction/Register Select 5 “R/W” - Read/Write LCD Registers 6 “E” - Clock 7-14 D0-D7 Data Pins

Eight-bit mode is best used when speed is required in an application and 10 I/O pins are available. Four-bit mode requires six bits. To wire a microcontroller to an LCD in four-bit mode, just the top four bits (DB4-7) are written to. The R/S bit is used to select whether data or an instruction is being transferred between the microcontroller and the LCD. If the bit is set, then the byte at the current LCD cursor position can be read or written. When the bit is reset, either an instruction is being sent to the LCD or the execution status of the last instruction is read back (whether or not it has completed). The different instructions available for use with the 44780 are shown in Table 6-3. The bit descriptions for the different commands are:

*Not used/ignored. This bit can be either 1 or 0 Set cursor move direction: ID Increment the cursor after each byte written to display if set S Shift display when byte written to display Enable display/cursor D Turn display on(1)/off(0) C Turn cursor on(1)/off(0) B Cursor blink on(1)/off(0) Move cursor/shift display SC Display shift on(1)/off(0) RL Direction of shift right(1)/left(0) Set interface length DL Set data interface length 8(1)/4(0) N Number of display lines 1(0)/2(1) F Character font 5x10(1)/5x7(0) Poll the busy flag BF This bit is set while the LCD is processing Move cursor to CGRAM/display A Address Read/write ASCII to the display H Data

Reading data back is best used in applications that require data to be moved back and forth on the LCD (such as in applications that scroll data between lines). The busy flag can be polled to determine when the last instruction that has been sent has completed processing. For most applications, there really is no reason to read from the LCD. I usually tie R/W to ground and just wait the maximum amount of time for each instruction (4.1 ms for clear- ing the display or moving the cursor/display to the home position, 160  s for all other commands). As well as making my application software simpler, it also frees up a micro- controller pin for other uses. Different LCDs execute instructions at different rates and to

272 PICmicro® MCU APPLICATION DESIGN AND HARDWARE INTERFACING

Figure 6-19 LCD data write waveform