Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip....

46
Microcontroller (1) Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, Germany Tel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected] Introduction to MicroProcessors and MicroControllers 1. INTRODUCTION 2 2. WHAT IS A MICROCOMPUTER? 3 2.1. WHAT IS A MICROPROCESSOR? 3 2.2. WHAT IS A MICROCONTROLLER? 4 2.3. WHAT IS AN EMBEDDED CONTROLLER? 5 3. THE MAJOR COMPONENTS OF A MICROCOMPUTER SYSTEM: 7 3.1. THE CPU 7 3.2. THE MEMORY 7 3.2.1. OPTIONS FOR STORING PROGRAMS. 8 3.3. THE I/O DEVICES 9 3.4. THE ADDRESS/DATA/CONTROL BUS (SYSTEM BUS) 12 4. A TYPICAL MICROPROCESSOR (Z80) 15 5. MICROCONTROLLER BASICS 17 5.0. A TYPICAL MIRCOCONTROLLER (I8051) 21 5.1. SOME OTHER POPULAR MICROCONTROLLERS 28 5.2. SPECIAL EASY CHIPS TO USE 31 5.3. INTEL 8052AH-BASIC 32 5.3.1. INSIDE THE 8052-BASIC 32 5.3.2. THE 8051 FAMILY 34 5.4. ELEMENTS OF THE 8052 AND 8052-BASIC 34 6. SPECIAL MICROCONTROLLER FEATURES 38 6.1. PERIPHERAL I/O 38 6.2. ADVANCED MEMORY OPTIONS 41 6.3. POWER MANAGEMENT AND LOW VOLTAGE 41 7. WRITING THE CONTROL PROGRAM 44 8. TESTING AND DEBUGGING 45 8.3. THE 8052-BASIC’S DEVELOPMENT SYSTEM 46 © by Heinz Rongen Forschungszentrum Jülich Zentrallabor für Elektronik 52425 Jülich, Germany email: [email protected]

Transcript of Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip....

Page 1: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (1)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

Introduction to

MicroProcessors and MicroControllers

1. INTRODUCTION 22. WHAT IS A MICROCOMPUTER? 32.1. WHAT IS A MICROPROCESSOR? 32.2. WHAT IS A MICROCONTROLLER? 42.3. WHAT IS AN EMBEDDED CONTROLLER? 53. THE MAJOR COMPONENTS OF A MICROCOMPUTER SYSTEM: 73.1. THE CPU 73.2. THE MEMORY 73.2.1. OPTIONS FOR STORING PROGRAMS. 83.3. THE I/O DEVICES 93.4. THE ADDRESS/DATA/CONTROL BUS (SYSTEM BUS) 124. A TYPICAL MICROPROCESSOR (Z80) 155. MICROCONTROLLER BASICS 175.0. A TYPICAL MIRCOCONTROLLER (I8051) 215.1. SOME OTHER POPULAR MICROCONTROLLERS 285.2. SPECIAL EASY CHIPS TO USE 315.3. INTEL 8052AH-BASIC 325.3.1. INSIDE THE 8052-BASIC 325.3.2. THE 8051 FAMILY 345.4. ELEMENTS OF THE 8052 AND 8052-BASIC 346. SPECIAL MICROCONTROLLER FEATURES 386.1. PERIPHERAL I/O 386.2. ADVANCED MEMORY OPTIONS 416.3. POWER MANAGEMENT AND LOW VOLTAGE 417. WRITING THE CONTROL PROGRAM 448. TESTING AND DEBUGGING 458.3. THE 8052-BASIC’S DEVELOPMENT SYSTEM 46

© by

Heinz RongenForschungszentrum JülichZentrallabor für Elektronik52425 Jülich, Germany

email: [email protected]

Page 2: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (2)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

1. Introduction

Microprocessors or Microcontrollers are widely used, as controlling component in allkind of instruments. In this case the Microcontroller with its peripheral extensions isthe major responsible component for the functionality of an instrument. If thecontroller fails, the complete instrument fails. Therefore this it very important tounderstand the major blocks inside of a microprocessor based system formaintenance and repair of such instruments. Such a controller system is call anembedded controller.

The microprocessor must often used for embedded controller systems are 8 bit µ-processors such as the 8080, 8085, Z80 or microcontrollers such as the 8751, 8052,8032, 8048 etc. The older versions of controllers where mounted into a 40 pin DIPpackage, the modern are SMD components.

Surface Mounted Devices (SMD) and the Surface Mounting Technology (SMT) arethe today’s technology for printed circuit boards in all application. With SMD devicesall kind of instruments are getting smaller, cheaper and also more reliable. But formaintenance of these SMT boards the users needs much more sophisticated toolsand experience to handle the SMD components without distroying the whole board.

This course demonstrates the building blocks and the repair of embedded controlsystems at two widely used standard processors.

♦ the TMPZ84c015 as an 8 bit microprocessor♦ the 8052 as an 8 bit microcontroller

All experiment boards are designed in SMD Technology for training soldering andunsoldering of SMD components.

Page 3: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (3)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

2. What is a Microcomputer?

A Microcomputer is a complete computer system comprising at least three majorcomponents, the microprocessor (CPU), Memory and IO peripheral components.A microcomputer could be a generalpurpose computer (like a PC) or asystem designed to fulfill a special task.(for example a controller system insidean instrument, microcontroller)

2.1. What is a Microprocessor?

A Microprocessor is a device containing functions equivalent to a small computer’sCentral Processing Unit (CPU). It is such capable of performing basic computerfunctions, an can be incorporated into system designs where such functions arerequired. A Microprocessor by definition means that this is only the centralprocessing unit, with instruction decoder, registers and Arithmetic Logic processingUnit.

A CPU does not include anymemory or I/O components.

Address / Data / Control Bus

CPU

MemoryEprom/Ram

I/OSIO/PIO

ALU

Data Bus

ProgrammCounter

Adress Bus

InstructionDecoder

Register

Page 4: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (4)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

2.2. What is a Microcontroller?

A Microcontroller is a Microcomputer in a single Chip. That means that amicrocontroller chip includes a microprocessor (CPU) as well as some often usedperipherals. A controller is used to control (makes sense!) some process or aspectof the environment. A typical microcontroller application is the monitoring of myhouse. As the temperature rises, the controller causes the windows to open. If thetemperature goes above a certain threshold, the air conditioner is activated.

As the process of miniaturization continued, all of the components needed for acontroller were built right onto one chip. A one chip computer, or microcontrollerwas born. A microcontroller is a highly integrated chip which includes, on one chip,all or most of the parts needed for a controller. The microcontroller could be called a"one-chip solution". It typically includes:

• CPU (central processing unit or the microprocessor)• EPROM/PROM/ROM (Read Only Memory for the program code)• RAM (Random Access Memory for the data)• I/O (input/output) devices (serial, parallel, ADC, DAC etc.)• Timers• Interrupt controller

By only including the features specific to the task (control), cost is relatively low. Atypical microcontroller has bit manipulation instructions, easy and direct access toI/O (input/output), and quick and efficient interrupt processing. Microcontrollers area "one-chip solution" which drastically reduces parts count and design costs.

Page 5: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (5)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

2.3. What is an Embedded Controller?

Simply (and naively stated) an embedded controller is a controller that is embeddedin a greater system. You COULD say that an embedded controller is a controller (orcomputer) that is embedded into some device for some purpose other than toprovide general purpose computing like a PC.In addition to control applications such as the above home monitoring system,microcontrollers are frequently found in embedded applications (embeddedcontrollers?). Among the many uses that you can find one or more microcontrollersappliances (microwave oven, refrigerators, television and VCRs, stereos),automobiles (engine control, diagnostics, climate control), environmental control(greenhouse, factory, home), instrumentation, aerospace, and thousands of otheruses.

A special application that microcontrollers are well suited for is data logging. Stickone of these chips out in the middle of a corn field or up in a balloon, and monitorand record environmental parameters (temperature, humidity, rain, etc.). Small size,low power consumption, and flexibility make these devices ideal for unattended datamonitoring and recording.

FlavorsMicrocontrollers come in many flavors and varieties. Depending on the power andfeatures that are needed, you might choose a 4 bit, 8 bit, 16 bit, or 32 bitmicrocontroller. In addition, some specialized versions are available which includefeatures specific for communications, keyboard handling, signal processing, videoprocessing, and other tasks.

worldwide Microcontroller Shipments (in millions of dollars)'90 '91 '92 '93 '94 '95 '96 '97

4-bit 1,393 1,597 1,596 1,698 1,761 1,826 1,849 1,881 8-bit 2,077 2,615 2,862 3,703 4,689 5,634 6,553 7,529 16-bit 192 303 340 484 810 1,170 1,628 2,191

worldwide Microcontroller Shipments (in Millions)'90 '91 '92 '93 '94 '95 '96 '97

4-bit 778 906 979 1036 1063 1110 1100 1096 8-bit 588 753 843 1073 1449 1803 2123 2374 16-bit 22 38 45 59 106 157 227 313

Notice that even the lowly 4-bit device is holding its own - what use is a 16-bit part ina toaster oven?Also notice that the 8-bit market just keeps growing, and will probablycontinue to grow. 8-bit devices account for over half of the market, and willeventually grab even more. Now do you understand why every siliconmanufacturer is really pushing their 8-bit microcontrollers?

Page 6: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (6)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

Page 7: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (7)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

3. The major components of a microcomputer system:

The major components of every computer are the CPU, Memory, I/O devices and thesystem bus. These components can be found in any computer system, anyway if it isa microprocessor or microcontroller based system.

3.1. The CPU

CPU means Central Processing Unit. The CPU is the kernel of each computer. Alldatas (instructions and user data) is read from the CPU into the CPU registers.Instructions (the program code) areread into the instruction register, nextthey are decoded in the instructiondecoder. Depending on the instructionas next following data fetches. Thedatas are stored in the arithemticregisters (accumulator), from there theare processed in te ALU (Arithmetic &Logic Unit). The ALU performs allarithmetical and logical processes onthe data. The result from the ALU iswritten back into a CPU register. Fromthere the data can be written back tothe memory or an I/O device.

The most inportant signal from a CPUare the adress bus, data bus andcontrol signals. These signalsconnecting the CPU to the memoryand the I/O devices.

3.2. The Memory

Every computer system needs a memory block. Memory can be external memorybuild by extra chips or the on chip memory of a microcontroller. In general there aretwo types of memory:

• Program memory• Data memory

Program memory is used to hold the application program. This must be memorywhich doesn’t loose his information at power down. At power up the CPU begins toread the instructions from this memory. In most microcomputer applications theprogram memory is a READ ONLY MEMORY (ROM). There are different types ofROM available. The most used is the EPROM. This chip could be programmed witha special programmer and could be erased by applying ultra-violet light. During the

Page 8: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (8)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

normal use of this chip inside of the microcomputer system this memory can not bewritten, only read.Data memory is used for the dynamic data which is generated by the applicationprogram and for the STACK. The stack is a portion of memory where the CPU saveshis own internal register data for calling a subroutine. Data memory must be able toread and write from the CPU, it is so called Random Access Memory (RAM).RAM chips looses the data when powered down.

The amount of memory in a microcomputersystem depends strongly on the application.There are small controller applicationswhich have only 512 Bytes ROM and 128Bytes RAM. Bigger microcontrollerapplication may have up to some Megabyteof EPROM and also RAM.Because of the 16 bit address bus of themost popular microcontrollers the addressspace is limited to 64 Kbyte. So you will findin many applications 32 Kbyte EROM and32 Kbyte RAM.

3.2.1. Options for storing programs.

Another consideration in circuit design is how to store programs. Instead of usingdisk storage, most microcontroller circuits store their programs on-chip. For one-of-kind projects or small-volume production, EPROM has long been the most popularmethod of program storage. Besides EPROMs, other options include EEPROM,ROM, nonvolatile (NV), or battery-backed, RAM, and Flash EPROM. The programmemory may be in the microcontroller chip, or a separate component. To save aprogram in EPROM, you must set the EPROM’s data and address pins to theappropriate logic levels for each address and apply special programming voltagesand control signals to store the data at the selected address. The programmingprocess is sometimes called burning the EPROM. You erase the contents byexposing the chip’s quartz window, and the circuits beneath it, to ultraviolet energy.Some microcontrollers contain a one-time-programmable, or field-programmable,EPROM. This type has no window, so you can’t erase its contents, but because it’scheaper than a windowed IC, it’s a good choice when a program is finished and thedevice is ready for quantity production. Several techniques are available forprogramming EPROMs and other memory chips. With a manual programmer, youflip switches to toggle each bit and program the EPROM byte by byte. This isacceptable for short programs, but quickly becomes tedious with a program of anylength. Computer control simplifies the job greatly. With an EPROM programmer thatconnects to a personal computer, you can write a program at your keyboard, save itto disk if you wish, and store the program in EPROM in a few easy steps. Data

Page 9: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (9)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

sheets for EPROMs rarely specify the number of erase and reprogramming cycles adevice is guaranteed for, but a typical EPROM should endure 100 erase/programcycles, and usually many more.

EEPROMs are much like EPROMs except that they are electrically erasable—noultraviolet source is required. Limitations of EEPROMs include slow speed, highcost, and a limited number of times that they can be reprogrammed (typically 10,000to 100,000).

ROMs are cost-effective when you need thousands of copies of a single program.ROMs must be factory-programmed and once programmed, can’t be changed.

NVRAM typically includes a lithium cell, control circuits, and RAM encapsulated in asingle IC package. When power is removed from the circuit, the lithium cell takesover and preserves the information in RAM, for 10 years or more. You canreprogram an NVRAM n infinite number of times, with the only limitation beingbattery life.

Flash EPROM is electrically erasable, like EEPROM, but most Flash devices eraseall at once, or in a few large blocks, rather than byte-by-byte like EEPROM. SomeFlash EPROMs require special programming voltages. As with EPROMs, the numberof erase/program cycles is limited.

The 8052-BASIC uses two types of program memory. An 8-kilobyte, or 8K, on-chipROM stores the BASIC-52 interpreter. For storing the BASIC-52 programs that youwrite, the BASIC-52 language has programming commands that enable you to saveprograms in external EPROM, EEPROM, or NVRAM.

Other memory. Most systems also require a way to store data for temporary use.Usually, this is RAM, whose contents you can change as often as you wish. UnlikeEPROM, ROM, EEPROM, and NVRAM, the contents of the RAM disappear whenyou remove power the chip (unless it has battery back-up).

Most microcontrollers include some RAM, typically a few hundred bytes. The 8052-BASIC has 256 bytes of internal RAM. A complete 8052-BASIC system requires atleast 1024 bytes of external RAM as well.

3.3. The I/O Devices

In general a CPU with memory is ready to run. But of what need is a computersystem without transaction to the real world? So every computer system needs someI/O devices. The word I/O-device is widespread. It could mean everything that isgood for interfacing to the external world.Typical I/O devices are:

♦ keyboard controller for inputs from the user♦ display controller for information to the user♦ parallel I/O to switch on/off some lights or relays

Page 10: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (10)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

♦ serial I/O to communicate with other computers♦ realtime clock so the computer knows the time and date♦ analog inputs to measure a physical phenomena♦ analog outputs to control a process

Finally, input/output (I/O) requires design decisions. Most systems require interfacesto things like sensors, keypads, switches, relays, and displays. Most microcontrollershave ports for interfacing to the world outside the chip. The 8052-BASIC uses manyof its ports for accessing external memory and performing other special functions,but some port bits are available for user applications, and you can easily increasethe available I/O by adding support chips.

Keyboards:A typical keyboard in embedded controller systemsis build with 16 keys designes as a 4 by 4 matrix.The keyboard controller scans the X lines one byone at a time and looks for an response at the ylines. If a key is pressed then thekeyboardcontroller knows from the X/Y informationwhich key has been pressed and stores thisinformation in an internal register. This informationcould be read from the CPU.

A commenly used keyboard controller is the74 C 922 or 74 C 923. In some applikations thereis no special keyboard controller. In this case thescan of the keyboard matrix is done by the CPUitself trough a parallel I/O interface (PIO).

Displays:The Hardware needed for the display depends strongly on the used display.One often used display are the so callend 7-segment display.This are LED based display modules for displaying only numbers0..9 and also the hex characters A..F. For driving the LEDs indiseof these 7-segment display you need a component which deliversthe needed current of about 10 mA per Segment. Also thedecoding from the binary number (0..9 for example) to thesegments which must be driven must be performed.The component 74 LS 47 is a typical binary to 7-segment display decoder.

Other Displays are the LCD Displays. Alpha-numeric modules display characters,numerals, symbols and some limited graphics. These LCD modules have their owncontroller. Interface is achieved via a bi-directional, parallel ASCII data bus.

Keyboard controller

to microprocessor

Page 11: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (11)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

Necessary features such as Character Generation, Display RAM Addressing, CursorScrolling, Blanking, and Handshake are all included. User programmable fonts aresupported. In summary, these modules are the simplest and most economic meansto communicate meaningfully between any micro-system and the outside world.Alpha-numeric modules range from 8 to 80 characters per line. One, two or fourcharacter lines may be chosen. Character height spans 0.130" (3.31 mm) to 0.500"(12.71 mm). Most formats are available in a variety of packages to meet variousmounting requirements.

Parallel I/O:Parallel I/O is the most used I/O device in small microcomputer applications. Aparallel I/O means that there are a number of static input or output bits. Theseoutputs can be used to drive some lights, to switch some relays, to drive a displayand so on. The input bits can be used to read information from switches etc.A simple parallel I/O can be done by a simple register component like a 74LS373.There are also some special parallel I/O components available, like the PIO 8255 orthe Z80-PIO. With components the user can switch every bit as an input or output,so these component are very flexible for many application.

Serial I/O:Serial I/O is used to send data over longer distances to another computer system,display systems (terminal) or to a printer.While speaking about serial interfaces there are two words which describe the typeof the serial interface:

DTE is acronym for Data Terminal Equipment.Examples of DTE is computers, printers & terminals.

DCE is acronym for Data Communication Equipment.Examples of DCE is modems.

Wiring a cable for DTE to DCE communication is easy. All wires goes straight frompin x to pin x.But wiring a cable for DTE to DTE (nullmodem) or DCE to DCE requires that somewires are crossed. A signal should be wire from pin x to the opposite signal at theother end. With opposite signals I mean for example Transmit & Send.

Realtime clock:A realtimeclock is useful in application where the computer must known the absolutetime and date, for example for switching on and off a peripheral device at a givenday and time. Typical realtime clock component are the RTC62421 or RTC 72421chip.

Analog inputs:

Page 12: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (12)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

Many applications need a analog input for measuring a physical signal like atemperature or pressure. For measuring a physical phenomena you first need asensor, which converts the physical phenomena into a electrical signal. Most of thesensors delivers a very small signal so at next you need some operational amplifiersto bring the signal into the level which is needed for the Analog to Digital Converter(ADC) (in most cases +/- 5 or +/- 10 Volt). The ADC itself is a single chip. There aremany ADCs on the market. All of them have different speed and resolution. Formicroprocessor applications there are many ADCs with converting time of about 10to 100 µs. For simple measurments there are ADCs with 8 bit resolution, mostly usedtoday are the 12 bit resolution, but there are also ADCs with 16, 18, 20 and 22 bitresolution used in microprocessor systems.

Analog outputs:Analog outputs are used to control external devices by a linear voltage. This couldbe a High-Voltage supply where you can adjust the High-Voltage with an inputvoltage or another example could be a heater where you can adjust the heatingpower by a external voltage. Digital to Analog Converters (DAC) are used togenerate a current or a voltage from the digital information written into a register. Allthe DACs need a operational amplifier behind their output pins to adjust their outputlevel to the voltage needed for the external device.Also here are a lot of DAC on the market, with bit resolutions ranging from 8, 12, upto 16 bit.

Because of the big ADC and DAC component market it is very difficult to give heresome component examples. Insteed I will say that there are some big componentcompanies which are great on the analog IO market. If you see a component with aLabel of: Analog Devices Burr Brown Maxim ...then in most cases these are components for the analog I/O section.

3.4. The Address/Data/Control Bus (system bus)

The system bus (address/data/control lines) is the connection between the severalcomponents of a microprocessor system. The data bus with depends on themicroprocessor (8, 16 or 32 bits), the address bus is at least 16 bit wide. The systembus is used for every datatransfer between the Memory and the CPU foroperationcode fetches, for datatransfer to and from the RAM for dynamic data fetchand also for data to and from the I/O devices. The transaction over the system buscan be grouped into two groups:

• a read cycle: data from the Memory or I/O device into the CPU• a write cycle: data from the CPU to the Memory or I/O device

The control lines of the system bus controls what kind of data transfer is in process.

Page 13: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (13)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

The most important control lines are:• the CHIPSELECT signal *CS• the READ signal *RD• the WRITE signal *WR

(asterix means that this signal is low aktiv)

Every bustransfer is started with the output of an address onto the address lines.The lower address line are direct connected to the Memory. Some address line (theupper lines) are used for address decoding. Adress decoding means that there is alogic circuits which decides based on the address what device (EPROM, RAM I/Odevice) should be activated. The address decoder then gives a unique CHIPSELECT (CS) signal to that device. For that, every device in amicroprocessorsystem needs a unique address.

The CS signal tells the device that it should transmit data in this bus cycle. At nextone of the signals RD or WR is activated from the CPU. This tells the device if itshould send data to the CPU (Read cycle) or receive data from the CPU (Writecycle).

Page 14: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (14)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

General Bustiming diagram:

Chip Select: *CS

Read signal: *RD

Write signal: *WR

Chip select to adevice

Chip select to adevice

a READ cyclea WRITE cycle

valid data fromthe deviceto theCPU

valid data fromthe CPU to thedevice

Data lines: D0..D7

valid addressfrom the CPU

valid addressfrom the CPU

Access time

Every bus cycle (Reads and Writes) starts with a valid address from the CPU. Asnext the address decoder generates a unique CHIP SELECT for one device. Thenthe RD or WR signal is activated from the CPU to tell wether it is a read or writeoperation. By a read operation the device has to drive the data to the data bus, thiscould take a short time (data access time), but the datas must be stable at the risingedge of the RD signal. With the rising edge of the RD signal the CPU latches thedata internal.In a write cycle the CPU itselfs drive the data bus. Also in this case it is not sure thatthe data is stable at the beginning of the cycle. The data must be stable at the risingedge of the WR cycle, so that the device could also latch the data with the risingedge of the WR signal.

Page 15: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (15)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

4. A typical microProcessor (Z80)

I get really nervous reading the trade press. Magazines will have you believe thatthe only viable processor for even the simplest applications is a 50 Mhz 486 or ascreaming RISC machine. How many designers are using these CPUs in theirembedded designs?Personally, I prefer 8 and 16 bit CPUs. They're cheap, they're cheap to interface to,and they are easy to work with. Remember that 16 and 32 bit machines will have 2or 4 ROM and RAM chips per word, compared to 1 for an 8 bit processor, greatlyincreasing memory costs. In fact, an 8 bit processor exactly matches the bus width ofthe vast majority of memories and peripherals. An 8 bit bus uses memory efficiently.Simpler circuitry, with fewer components, can be used.

I feel four processor families can satisfy most embedded designs. I'll leave out 4 bitchoices, as these applications are often so specialized that a custom or semi-customchip is often the most cost effective solution. My choices are the 8051 family, theZ80 family, the 80186 (and V-Series) families, and the 68000 and its derivatives.In this document I will do my explanations about microprocessor on the example ofthe Z80 and his derivates.

Current Z80 Technology

The Z80 is essentially unchanged from the original version introduced in the mid-70s. Now CMOS versions are common, and clock rates have skyrocketed. Zilog'snewest offering runs at 20 Mhz. This speed is no panacea- it comes at the price ofexpensive ROMs and RAMs. Still, even at 6 to 10 Mhz the Z80 has respectableperformance. It would be a terrible Windows machine, but is more than adequate foran awful lot of embedded systems.

The Z80 itself is attractive due to its low cost and wide availability. It's pretty easy tofind Z80s for less than a buck. Tools are everywhere. Though its index instructionsare a little crude, it is a far better C machine than, say, the 8051.The Z80 in isolation would be a dead-end line. What makes it interesting is the highintegration derivatives CPUs spawned by the architecture. All four of the processorfamilies I mentioned earlier exist in multiple proliferation versions. A processor byitself is useful; one integrated with a number of on-chip peripherals is compelling.

The 64180 is a Hitachi-supplied Z80 core with numerous on-chip "extras". Zilog'sversion is the Z180, which is essentially the same part. As of this writing, Zilog sellsparts running at speeds to 15 Mhz. The 64180/Z180 microprocessor integratesmany of the functions traditionally assigned to peripheral circuitry onto a single chip.The designers picked an architecture compatible with the Z80, giving Z80 users acompletely software compatible upgrade path. Old Z80 designs can be converted tothe 64180 with essentially no loss in software investment. New designs will benefitfrom the processor's low cost, powerful instruction set, minute power consumption,and high level of integration.

Page 16: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (16)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

Both Toshiba and Zilog sell the 84013 and 84015, which are Z80 cores withconventional Z80 peripherals integrated on-board. These processors are naturalmigration paths for current users of Z80s wishing to reduce systems costs.Both the 84013 and the 84015 include one SIO (Z80-specific Serial I/O), and oneCTC (again, a Z80-specific timer part). The SIO and CTC are functionally identical tothe discrete chip SIO/CTC used in so many older designs. In addition, the newerparts include a watchdog timer and clock generator. The 84015 comes in a 100 pinquad flat pack. To take advantage of the extra pins the vendors added in a Z80-likePIO (parallel I/O) port, with 16 parallel lines and 4 handshaking likes.

Page 17: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (17)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

5. Microcontroller Basics

This chapter introduces you to the world of microcontrollers, including definitions,some history, and a summary of what’s involved in designing and building amicrocontroller project.A microcontroller is a computer-on-a-chip, or, if you prefer, a single-chip computer.Micro suggests that the device is small, and controller tells you that the device mightbe used to control objects, processes, or events. Another term to describe amicrocontroller is embedded controller, because the microcontroller and its supportcircuits are often built into, or embedded in, the devices they control. You can findmicrocontrollers in all kinds of things these days. Any device that measures, stores,controls, calculates, or displays information is a candidate for putting amicrocontroller inside. The largest single use for microcontrollers is in automobiles,just about every car manufactured today includes at least one microcontroller forengine control, and often more to control additional systems in the car. In desktopcomputers, you can find microcontrollers inside keyboards, modems, printers, andother peripherals. In test equipment, microcontrollers make it easy to add featuressuch as the ability to store measurements, to create and store user routines, and todisplay messages and waveforms. Consumer products that use microcontrollersinclude cameras, video recorders, compact-disk players, and ovens. And these arejust a few examples.A microcontroller is similar to the microprocessor inside a personal computer.Examples of microprocessors include Intel’s 8086, Motorola’s 68000, and Zilog’sZ80. Both microprocessors and microcontrollers contain a central processing unit, orCPU. The CPU executes instructions that perform the basic logic, math, and data-moving functions of a computer. To make a complete computer, a microprocessorrequires memory for storing data and programs, and input/output (I/O) interfaces forconnecting external devices like keyboardsand displays. In contrast, a microcontroller is a single-chip computer because itcontains memory and I/O interfaces in addition to the CPU. Because the amount ofmemory and interfaces that can fit on a single chip is limited, microcontrollers tend tobe used in smaller systems that require little more than the microcontroller and a fewsupport components. Examples of popular microcontrollers are Intel’s 8052(including the 8052-BASIC, which is the focus of this book), Motorola’s 68HC11, andZilog’s Z8.

A Little HistoryTo understand how microcontrollers fit into the always-expanding world ofcomputers, we need to look back to the roots of microcomputing. In its January 1975issue, Popular Electronics magazine featured an article describing the Altair 8800computer, which was the first microcomputer that hobbyists could build and programthemselves. The basic Altair included no keyboard, video display, disk drives, orother elements we now think of as essential elements of a personal computer. Its8080 microprocessor was programmed by flipping toggle switches on the front panel.Standard RAM was 256 bytes and a kit version cost $397 ($498 assembled). Abreakthrough in the Altair’s usability occurred when a small company calledMicrosoft offered a version of the BASIC programming language for it.

Page 18: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (18)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

Of course, the computer world has changed a lot since the introduction of the Altair.Microsoft has become an enormous software publisher, and a typical personalcomputer now includes a keyboard, video display, disk drives, and Megabytes ofRAM. What’s more, there’s no longer any need to build a personal computer fromscratch, since mass production has drastically lowered the price of assembledsystems. At most, building a personal computer now involves only installingassembled boards and other major components in an enclosure.A personal computer like Apple’s Macintosh or IBM’s PC is a general-purposemachine, since you can use it for many applications—word processing,spreadsheets, computer-aided design, and more—just by loading the appropriatesoftware from disk into memory.Interfaces to personal computers are for the most part standard ones like those tovideo displays, keyboards, and printers.

But along with cheap, powerful, and versatile personal computers has developed anew interest in small, customized computers for specific uses. Each of these smallcomputers is dedicated to one task, or a set of closely related tasks. Addingcomputer power to a device can enable it to do more, or do it faster, better, or morecheaply. For example, automobile engine controllers have helped to reduce harmfulexhaust emissions. And microcontrollers inside computer modems have made iteasy to add features and abilities beyond the basic computer-to-phone-lineinterface.In addition to their use in mass-produced products like these, it’s also becomefeasible to design computer power into one-of-a-kind projects, such as anenvironmental controller for a scientific study or an intelligent test fixture thatensures that a product meets its specifications before it’s shipped to a customer. Atthe core of many of these specialized computers is a microcontroller. The computer’sprogram is typically stored permanently in semiconductor memory such as ROM orEPROM. The interfaces between the microcontroller and the outside world vary withthe application, and may include a small display, a keypad or switches, sensors,relays, motors, and so on. These small, special-purpose computers are sometimescalled single-board computers, or SBCs. The term can be misleading, however,since the computer doesn’t have to be on a single circuit board, and many types ofcomputer systems, such as laptop and notebook computers, are now manufacturedon a single board.

New ToolsTo design and build a computer-controlled device, you need skills in both circuitdesign and software programming. The good news is that a couple of recentadvances have simplified the tasks involved.One is the introduction of microcontrollers themselves, since they contain all of theelements of a computer on a single chip. Using a microcontroller can reduce thenumber of components and thus the amount of design work and wiring required for aproject. The 8052-BASIC microcontroller even includes its own programminglanguage, called BASIC-52. The other development is personal computersthemselves. A desktop computer can help tremendously by serving as a host systemfor writing and testing programs. As you are developing a project, you can use a

Page 19: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (19)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

serial link to connect the host system to a target system, which contains themicrocontroller circuits you are testing. You can then use the personal computer’skeyboard, video display, disk drives, and other resources for writing and testingprograms and transferring files between the two systems.

The 8052-BASIC chip described in this book is perfect for many simpler applications,especially control and monitoring tasks. Because the chip is easy to use, it’s a goodway to learn about microcontrollers and computers in general. Although you can’t dothe most complex projects with it, you can do a lot, at low cost and without a lot ofhassle.

Choosing a chip.Does it matter which microcontroller chip you use? All microcontrollers contain aCPU, and chances are that you can use any of several devices for a specific project.Within each device family, you’ll usually find a selection of family members, eachwith different combinations of options. For example, the 8052-BASIC is a member ofthe 8051 family of microcontrollers, which includes chips with program memory inROM or EPROM, and with varying amounts of RAM and other features. You selectthe version that best suits your system’s requirements.

Microcontrollers are also characterized by how many bits of data they process atonce, with a higher number of bits generally indicating a faster or more powerfulchip. Eight-bit chips are popular for simpler designs, but 4-bit, 16-bit, and 32-bitarchitectures are also available. The 8052-BASIC is an 8-bit chip. Powerconsumption is another consideration, especially for battery-powered systems. Chipsmanufactured with CMOS processes usually have lower power consumption thanthose manufactured with NMOS processes. Many CMOS devices have specialstandby or “sleep” modes that limit current consumption to as low as a fewmicroamperes when the circuits are inactive. Using these modes, a data logger canreduce its power consumption between samples, and power up only when it’s time totake data. The 8052-BASIC chip is available in both NMOS and CMOS versions.The original 8052-BASIC was an NMOS chip, offered directly from Intel. (Intel’s termfor its NMOS process is HMOS.) Although Intel never offered a CMOS versiondirectly, Micromint became a source by ordering a batch of CMOS 8052’s with theBASIC-52 programming language in ROM. The CMOS version, the 80C52-BASIC,has maximum power consumption of 30 milliamperes, compared to 175 milliamperesfor the NMOS 8052-BASIC. All microcontrollers have a defined instruction set, whichconsists of the binary words that cause the CPU to carry out specific operations. Forexample, the instruction 0010 0110 tells an 8052 to add the values in two locations.The binary instructions are also known as operation codes, or opcodes for short.The opcodes perform basic functions like adding, subtracting, logic operations,moving and copying data, and controlling program branching. Control circuits oftenrequire reading or changing single bits of input or output, rather than reading andwriting a byte at a time. For example, a microcontroller might use the eight bits of anoutput port to switch power to eight sockets. If each socket must operateindependently of the others, a way is needed to change each bit without affecting the

Page 20: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (20)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

others. Many microcontrollers include bit-manipulation (also called Boolean)opcodes that easily allow programs to set, clear, compare, copy, or perform otherlogic operations on single bits of data, rather than a byte at a time.

Page 21: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (21)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

5.0. A typical mircoController (i8051)

The 8051 is an 8 bit microcontroller originally developed by Intel in 1980. It is theworld's most popular microcontroller core, made by many independentmanufacturers (truly multi-sourced). There were 126 million 8051s (and variants)shipped in 1993!!

A typical 8051 contains:⇒ CPU with Boolean processor⇒ 5 or 6 interrupts:

2 are external, 2 priority levels⇒ 2 or 3 16-bit timer/counters⇒ programmable full-duplex serial port (baud rate provided by one of the timers)⇒ 32 I/O lines (four 8-bit ports)⇒ RAM⇒ ROM/EPROM in some models

Blockdiagram of the 8052 microcontroller:

Page 22: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (22)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

The 8051 architecture is a tad bizarre, but then so are the architectures of mostmicrocontrollers due to their specialization (check out the PIC for creativity). Onevexing problem with the 8051 is its very non-orthogonal instruction set - especiallythe restrictions on accessing the different address spaces. However, after some timeprogramming the chip, you can get used to it - maybe even appreciate it.One strong point of the 8051 is the way it handles interrupts. Vectoring to fixed 8-byte areas is convenient and efficient. Most interrupt routines are very short (or atleast they should be), and generally can fit into the 8-byte area. Of course if yourinterrupt routine is longer, you can still jump to the appropriate routine from withinthe 8 byte interrupt region.

The 8051 instruction set is optimized for the one-bit operations so often desired inreal-world, real-time control applications. The Boolean processor provides directsupport for bit manipulation. This leads to more efficient programs that need to dealwith binary input and output conditions inherent in digital-control problems. Bitaddressing can be used for test pin monitoring or program control flags.

8051 FlavorsThe 8051 has the widest range of variants of any embedded controller on themarket. The smallest device is the Atmel 89c1051, a 20 Pin FLASH variant with 2timers, UART, 20mA. The fastest parts are from Dallas, with performance close to 10MIPS! The most powerful chip is the Siemens 80C517A, with 32 Bit ALU, 2 UARTS,2K RAM, PLCC84 package, 8 x 16 Bit PWMs, and other features.

Among the major manufacturers are: AMD Enhanced 8051 parts (no longer producing 80x51 parts) Atmel FLASH and semi-custom parts Dallas Battery backed, program download, and fastest variants Intel 8051 through 80c51gb / 80c51sl Matra 80c154, low voltage static variants OKI 80c154, mask parts Philips 87c748 through 89c588 - more variants than anyone else Siemens 80c501 through 80c517a, and SIECO cores SMC COM20051 with ARCNET token bus network engine SSI 80x52, 2 x HDLC variant for MODEM use

8051 representatives and approximate prices (in USD $)There are many, many varieties of 8051 out there. This is only a small sampling oftypical prices on Intel chips.

8031 (128 bytes RAM) 3.5980C31 (CMOS version of previous) 6.958051AH (256 bytes RAM) 6.958052AHBASIC (w/Basic interpreter built in) 29.958751 (4K EPROM, 128 bytes RAM) 26.9587C51 (CMOS version of previous) 39.95

Page 23: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (23)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

89C2051 (ATMEL 2K FLASH, 128 bytes RAM, 20-pin) 3.30

Page 24: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (24)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

8051 Types of MemoryBefore we delve into the guts of the 8051, it is important to define the four types ofmemory that are available. The distinction between each type of memory is importantbecause different assembly language instructions are used to access each type ofmemory, and each type of memory has unique qualities which must be consideredwhen first designing the hardware and/or software.

The four types of memory are:Internal RAM. The microcontroller contains a small amount of on-chip RAM which isused primarily for internal program registers, the stack, and often user variableswhich need to be accessed quickly or on a frequent basis. In the 8051 and 8031models, the total amount of Internal RAM is 128 bytes. In the 8052 and 8032 models,the total amount of Internal RAM is 256 bytes (an easy way to remember this is bylooking at the last digit of the model of the chip: a "1" means 128 bytes, and a "2"means 256 bytes). It is important to remember that the internal "R" registers, thestack, and the "bit registers" (more on all these later) all share these precious 128 or256 bytes of Internal RAM. Thus it is often important to use space within InternalRAM for variable storage on a very sparing basis to avoid problems, particularlystack overflows. The Internal RAM is volatile (it's contents are lost when the powerfails) and is the fastest type of memory available in an 8051 architecture since it is"on-chip."

External RAM. The microcontrollers ability to accept external RAM allows you tohandle greater quantities of data than would otherwise be possible if you wererestricted to the 8051's Internal RAM. As the name suggests, External RAM isadditional Random-Access-Memory which is external to the chip itself. ExternalRAM, like Internal RAM, is volatile so it's contents will be lost when the power fails.Like EPROM memory, External RAM is limited to 64k (Note: you may have 64k ofRAM and 64k of EPROM at the same time). External RAM is not as fast as InternalRAM since the microcontroller has to move the bytes to/from the External RAMchip(s). Like External EPROM memory, the use of External RAM will cause you tolose 16 of the 32 input/output lines normally available. Note: If you use bothExternal EPROM and External RAM, you will lose the same 16 input/output line.That is to say, you don't lose 16 bits for each type of External memory used, just forthe fact that some type of external memory is used.

Internal EPROM. Several models of the 8051 microcontroller (specifically, the 8751and the 8752) offer an on-chip EPROM. This means rather than using an externalEPROM chip, you may burn your program directly into the 8751 (or 8752). This hasa number of important advantages:• Since your program is stored on-chip, an additional EPROM chip (and circuit design to support it) is unnecessary.• When your program is stored on-chip you do not lose the 16 input/output lines

that you lose when using an External EPROM.• The chip can be configured to prevent the contents of the EPROM from being read off the chip.

Page 25: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (25)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

A disadvantage of external EPROM’s is that anyone can read the contents andreverse engineer your code. Using Internal EPROM, you can burn your programonto the 8751/8752 and instruct it to deny read access by would-be hackers. Thedrawbacks to Internal EPROM’s is that the chips themselves are somewhat moreexpensive and that the amount of EPROM space is limited to 4k (8751) or 8k (8752)which may make it a non-option if your program is large.

External EPROM. The microcontroller is generally pretty useless unless you cansomehow run your "program" on it. One of the most common ways of running yourprogram is to compile it and subsequently "burn" it into a separate EPROM chip. The8051 can then be attached to the EPROM at the hardware level such that themicrocontroller will run the program stored in the EPROM. Since your code is"burned" into the EPROM, the contents are not lost when the power fails. However,since it is a type of "ROM" (Read Only Memory) it is not possible for your programto modify the data stored therein. Thus, it is ideal for storing your program and otherconstants. The 8051 can access up to 64k (65536 bytes) of EPROM memory. Yourprograms, thus, are limited to 64k (there are actually tricks involving specializedcircuit design and specialized support software that can break the 64k program limit,but without taking these fancy steps the limit is 64k). Additionally, if an ExternalEPROM is used you will lose 16 of the 32 input/output lines normally available toyou.

Page 26: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (26)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

8051 Memory Access ProcedureWhen using externel memory with the 8052 then port 0 and port 1 are used as amultiplexed address/data bus. By this you loose 16 of the 32 I/O bits, but for this youcan extend your external address range to 64 Kbyte external locations. (EPROM,RAM or also memory mapped I/O devices)A multiplexed address/data bus means that the lower lines of this 16 bit interface isused as an part of the adress and later as datalines. The access to external memoryis as followed. Whenever the 8051 requires access (either read or write) to ExternalData Memory (RAM), the following sequence of events takes place:

• The full address is loaded into pins Addr0 through Addr15.• The ALE pin is strobed for a short period of time.• The lower byte of the address (Addr0 through Addr7) is replaced by the bits

of the data to be written.• After a short delay, either the WR, RD or PSEN pin is strobed to execute

the memory access operation. WR and RD deal with access to externaldata memory (RAM) whereas PSEN deals with access to external codememory (such as from an EPROM).

The logic behind this is that by doubling the function of pins port0-0 through port0-7more effective use of pins is achieved. That is to say, if these pins did not servedouble-functions the 8051 would either require an additional 8 pins (48 pins insteadof 40) or would cause an additional 8-bit port to become unavailable when externalmemory was used. Since neither of these are desirable options, the designers of the8051 chose to use pins port0-0 through port0-7both to transmit the low-byte of theaddress and to also transmit the data itself.As you can see by reviewing the four step procedure above, the ALE pin is strobedwhen pins port0-0 through port0-7 contain the low-byte of the address. When ALE is

Page 27: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (27)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

strobed, therefore, we need to store and hold the value of the low-byte of memory sothat those 8 bits are still available when the actual read or write operation takesplace (when RD or WR is strobed). This is easily accomplished using a simple OctalLatch, such as the 74HCT373.

Page 28: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (28)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

5.1. Some other popular microcontrollers

Some common microcontrollers are described below. A common question is "whatmicrocontroller should I use for...?" Well, that's a tough one. The best advice wouldbe to choose a chip that has a full set of development tools at the price you canafford, and good documentation. For the hobbyist, the Intel 8051, Motorola 68hc11,or Microchip PIC would all make suitable choices.

8048 (Intel)The granddaddy of 'em all, the first microcontroller, it all started here! Although a bitlong in the tooth and a bit kludgey in design (at least by today's standards), it is stillvery popular due to its very low cost, availability, and wide range of developmenttools. Modified Harvard architecture with program ROM on chip with an additional 64to 256 bytes of RAM also on chip. I/O is mapped in its own space.

8051 (Intel and others)The 8051, Intel's second generation of microcontrollers, rules the microcontrollermarket at the present time. Although featuring a somewhat bizarre design, it is avery powerful and easy to program chip (once you get used to it).Modified Harvard architecture with separate address spaces for program memoryand data memory. The program memory can be up to 64K. The lower portion (4K or8K depending on type) may reside on chip. The 8051 can address up to 64K ofexternal data memory, and is accessed only by indirect addressing. The 8051 has128 bytes (256 bytes for the 8052) of on-chip RAM, plus a number of specialfunction registers (SFRs). I/O is mapped in its own space.The 8051 features the so-called "Boolean processor". This refers to the wayinstructions can single out bits just about anywhere (RAM, accumulators, I/Oregisters, etc.), perform complex bit tests and comparisons, and then executerelative jumps based on the results. Piles of software, both commercial and free, areavailable for the 8051 line. Many manufacturers supply what must be a hundreddifferent variants of this chip for any requirement.

80c196 (MCS-96)The third generation of Intel microprocessors, the 80c196 is a 16 bit processor.Originally fabricated in NMOS (8096), it is now mainly available in CMOS.Among the many features it includes are: hardware multiply and divide, 6 addressingmodes, high speed I/O, A/D, serial communications channel, up to 40 I/O ports, 8source priority interrupt controller, PWM generator, and watchdog timer.

80186,80188 (Intel)These chips are, in essence, microcontroller versions of the 8086 and 8088 (ofIBM/PC fame). Included on the chip are: 2 channels of DMA, 2 counter/timers,programmable interrupt controller, and dynamic RAM refresh. There are severalvariations including: low power versions, variations with serial ports, and so on.

80386 EX (Intel)

Page 29: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (29)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

The 80386 EX is of course a 386 in microcontroller clothing. Included on the chipare: serial I/O, power management, DMA, counter/timers, programmable interruptcontroller, and dynamic RAM refresh. And of course, all of the power of the 386microprocessor.

TMS370 (Texas Instruments)It is similar to the 8051 in having 256 registers, A and B accumulators, stack in theregister page, etc. It also has a host of onboard support devices, some membershave all of them while others have a subset, the peripherals include: RAM, ROM(mask, OTP, or EEPROM), 2 timers (configurable as timers/ counters/ comparators/PWM output), watchdog timer, SCI (synchronous serial port), SPI (asynchronousserial port), A/D (8 bit, 8 channel), interrupts.

6805 (Motorola)The 6805 is based loosely on the manufacturer's earlier 6800, with some similaritiesto the 6502. It has a Von-Neuman architecture in which instructions, data, I/O, andtimers all share the same space. Stack pointer is 5 bits wide which limits the stack to32 bytes deep. Some members of this family include on chip A/D, PLL frequencysynthesizer, serial I/O, and software security.

68hc11 (Motorola and others)The popular 68hc11 is a powerful 8-bit data, 16-bit address microcontroller fromMotorola (the sole supplier) with an instruction set that is similar to the older 68xxparts (6801, 6805, 6809). The 68hc11 has a common memory architecture in whichinstructions, data, I/O, and timers all share the same memory space.Depending on the variety, the 68hc11 has built-in EEPROM/OTPROM, RAM, digitalI/O, timers, A/D converter, PWM generator, pulse accumulator, and synchronousand asynchronous communications channels. Typical current draw is less than20ma.

PIC (MicroChip)The PIC microcontrollers were the first RISC microcontrollers. RISC generallyimplies that simplicity of design allows more features to be added at lower cost, andthe PIC line is no exception. Although having few instructions (eg. 33 instructions forthe 16C5X line versus over 90 for the Intel 8048), the PIC line has a wealth offeatures included as part of the chip. Separate buses for instructions and data(Harvard architecture) allows simultaneous access of program and data, andoverlapping of some operations for increased processing performance. Thebenefits of design simplicity are a very small chip, small pin count, and very lowpower consumption.PIC microcontrollers are rapidly gaining in popularity. They are being featured moreand more often in construction projects in popular hobbyist magazines, and arechalking up a good number of design wins. Due to their low cost, small size, and lowpower consumption, these microcontrollers can now be used in areas thatpreviously wouldn't have been appropriate (such as logic circuits). They arecurrently available in three lines: the PIC16C5x, PIC16Cxx, and PIC17Cxx families.

Page 30: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (30)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

HD64180 (Hitachi)A powerful microcontroller with full Z80 functionality plus: extended memorymanagement, two DMA channels, synchronous and asynchronous communicationschannels, timers, and interrupt controller. Some versions of this chip also includeEPROM, RAM, and PIO (programmable input/output). It runs Z80 code in fewerclock cycles than the Z80 and adds in hardware multiply and a few otherinstructions.

Page 31: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (31)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

TMPZ84C015B (Toshiba)A powerful microcontroller with full Z80 functionality plus: Counter/Timer, Serial I/O(SIO), Parallel I/O (PIO), Watchdog, Interrupt controller. It runs Z80 code in fewerclock cycles than the Z80 and adds in hardware multiply and a few otherinstructions.

Z8 (Zilog)A "loose" derivative of the Zilog Z80, the Z8 is actually a composite of severaldifferent architectures. Not really compatible with the Z80 peripherals. Has aunique architecture with three memory spaces: program memory, data memory, anda CPU register file. On-chip features include UART, timers, DMA, up to 40 I/Olines. Some versions include a synchronous/asynchronous serial channel. Featuresfast interrupt response with 37 interrupt sources. The Z8671 has Tiny Basic inROM. The Super-8 is just that, a super version of the Z8 with more of everything.

5.2. Special Easy chips to use

MicroChip PIC '5x seriesWith only 33 instructions, this chip is definitely easy to use! These chips simply needpower, ground, and 1 of 4 different timing circuits. With I/O pins that are beefy(25mA per pin sink, 20mA per pin source) and drive both high and low, interfacing issuper easy. It's great to hook LEDs and such directly to output pins with only aresister in-line!

Page 32: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (32)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

5.3. Intel 8052AH-BASIC

This is a 8052 with internal 8 Kbytes Prom. The Prom already contains a BasicInterpreter. You can download high level Basic code from your host.

5.3.1. Inside the 8052-BASIC

This chapter introduces you to the 8052-BASIC chip, including the kinds of projectsyou can do with it, what equipment, materials, and skills you need in order to designand build an 8052-BASIC project, and a pin-by-pin look at the chip and its abilities.

PossibilitiesThe 8052-BASIC microcontroller is an easy-to-use, low-cost, and versatile computer-on-a-chip. It’s ideal for projects that require more than an assortment of logic gates,but less than a complete desktop computer system with a full keyboard, display, anddisk drives. If you’re interested in doing more with computers than simply runningapplications programs, the 8052-BASIC gives you a chance to design and build asystem from the ground up. With a few support chips and a program stored inmemory, you can use the 8052-BASIC to sense, measure, and control processes,events, or conditions.

The 8052-BASIC is actually two products in one: it’s an 8052 microcontroller, withthe BASIC-52 programming language on-chip. To begin using the 8052-BASIC, youneed a minimum circuitconsisting of the 8052-BASICand some support components,plus a personal computer. Thisbook contains specificinstructions for use with “IBM-compatible,” or MS-DOS,computers, but you can use anycomputer that has an RS-232serial port and communicationssoftware to go with it.

The Figure below shows thebasic setup.

With an 8052-BASIC circuit connected by a serial link to a personal computer, youhave a complete development system with these abilities:• You can write and run BASIC programs. You use the keyboard, video display, and

other resources of the personal computer to type and view the programs andcommands that the 8052-BASIC system executes. BASIC-52 is an interpretedlanguage whose programs do not require an additional assembling or compilingstep. You can run programs or execute commands immediately after you writethem.

Page 33: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (33)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

• You can use BASIC-52’s programming functions to permanently store yourprograms in EPROM or other nonvolatile memory. You don’t need a separateEPROM programmer.

• You can also store programs on your personal computer’s disk. You can write oredit programs on your personal computer, and then upload them to the 8052-BASIC system.

• To the basic circuits, you can add displays, switches, keypads, relays, and othercomponents, depending on the needs of your project.

• After program development, you can disconnect the link to the personal computerand let the 8052-BASIC system run its stored program on its own.

LimitsNo single product is ideal for every use. These are some of the limitations to the8052-BASIC:♦ Program execution can be slow, compared with programs that run on more

powerful computers, or programs written in assembly language. A typical programline in BASIC-52 takes several milliseconds to execute. Because of this, there aresome tasks that BASIC-52 just can’t handle—for example, detecting andresponding to an interrupt within a few microseconds. But for many control,monitoring, and other tasks, BASIC-52 is fine. For example, a weather station thatsenses conditions once per minute and stores or displays the results doesn’t needsuper-fast response. And, if necessary, you can call an assembly-languageroutine for a portion of a program where speed is critical. Even if you write yourprograms in assembly language, C, or another language, you can use the 8052-BASIC system as a development system that enables you to upload your programto memory, run the program, and test and debug your programs and circuits.

♦ Another limitation of the 8052-BASIC is that a complete project requires additionalcomponents. If you’re looking for a true single-chip solution, the 8052-BASIC isn’tit. Even a minimal system requires an external RAM chip, and most systems alsohave an external EPROM or other non-volatile memory. The serial link and otheroptional functions also use some of the on-chip timers and input/output ports, sothese may not be available for other uses. Still, the 8052-BASIC lets you to do alot with a little. When needed, you can easily add chips to expand the input/outputports, timers, and other functions.

♦ And finally, don’t expect BASIC-52 to have the abilities of QBasic, Visual Basic orother BASIC programming languages that you may use on your personalcomputer. BASIC-52 is more capable than many other single-chip BASICs. Itincludes features like loops, subroutines, string handling, and even floating-pointmath for handling factional quantities. But there are some primitive aspects to thelanguage. For example, the on-line editing functions are limited. Once you write aprogram line, you can change it only by retyping from the beginning. Thelimitations are understandable, because the entire programming language has tofit in the 8052’s 8 kilobytes of ROM. Fancy editing and other features just aren’tfeasible in this small space.

Page 34: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (34)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

There are solutions here as well. You can get around many of the editing limitationsby writing and editing programs off-line, using your personal computer and texteditor, and then uploading to the 8052-BASIC system. And, there are software andhardware products that enhance BASIC-52 and make it easier to use, especially forlonger, more complex programming jobs.

5.3.2. The 8051 Family

At the core of the 8052-BASIC is an 8052 microcontroller, a member of the 8051microcontroller family. Intel Corporation introduced the 8051 in 1980. Since thattime, 8051-family chips have been used as the base of thousands of products. Manyothercompanies, including Philips, Siemens, Dallas Semiconductor, OKI, Fujitsu, andHarris-Matra now also make 8051-family chips. Some companies have expanded the8051 family by offering compatible chips with additional features. Table belowsummarizes the differences among popular 8051-family chips. The 8052 is anenhanced 8051, with an extra timer and more RAM and ROM. The 8031 and 8032are identical to the 8051 and 8052, except that the ROM area is unused, andprogram code must be stored in an external EPROM or other memory chip.

Differences among 8051-family chips.

Chip ProgramMem. Kilobyte RAM (bytes) Timers8051 ROM 4 128 28052 ROM 8 256 38031 none - 128 28032 none - 256 38751 EPROM 4 128 28752 EPROM 8 256 3

· 80C51, 80C52, 80C31, and so on are CMOS versions of above.· 80C51FA/B/C add more versatile timers and an enhanced serial channel.· 8052-BASIC has the BASIC-52 programming language in ROM.· Packages include 40-pin DIP, 40-lead PLCC, and 44-pin QFP.

The 8052, like other 8051-family chips, is available in NMOS and CMOS versions.

5.4. Elements of the 8052 and 8052-BASIC

These are the major elements of the 8052, plus the enhancements included in the8052-BASIC:

CPU The CPU, or central processing unit, executes program instructions. Types ofinstructions include arithmetic (addition, subtraction), logic (AND, OR, NOT), datatransfer (move), and program branching (jump) operations. An external crystalprovides a timing reference for clocking the CPU.

Page 35: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (35)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

ROM ROM (read-only memory) is the read-only memory that is programmed intothe chip in the manufacturing process. In the 8052-BASIC, the ROM contains theBASIC-52 interpreter program that the 8052 executes on boot-up. As far as thehardware is concerned, this is the only difference between the ordinary 8052 and the8052-BASIC.

RAM RAM (random-access memory) is where programs store information fortemporary use. Unlike ROM, the CPU can write to RAM as well as read it. Anyinformation stored in RAM is lost when power is removed from the chip. The 8052has 256 bytes of RAM. BASIC-52 uses much of this for its own operations, with a fewbytes available to users.

I/O Ports I/O (Input/Output) Ports enable the 8052 to read and write to externalmemory and other components. The 8052 has four 8-bit I/O ports (Ports 0-3). As thename suggests, the ports can act as inputs (to be read) or outputs (to be written to).Many of the port bits have optional, alternate functions relating to accessing externalmemory, using the on-chip timer/counters, detecting external interrupts, andhandling serial communications. BASIC-52 assigns alternate functions to theremaining port bits. Some of these functions are required by BASIC-52, while othersare optional. If you don’t use an alternate function, you can use the bit for anycontrol, monitoring, or other purpose in your application.

Accessing external memory. The largest alternate use of the ports has to do withaccessing external memory. Although the 8052 is a single-chip computer, acomplete 8052-BASIC system requires additional components. It must have externalRAM in addition to the 8052’s internal RAM, and most systems also have EPROM,EEPROM, or battery-backed RAM for permanent storage of BASIC-52 programs.Accessing this external memory uses all of Ports 0 and 2, plus bits 6 and 7 of Port 3,to hold data, addresses, and control signals for reading and writing to externalmemory. Data here refers to a byte to be read or written, and may be any type ofinformation, including program code. The address defines the location in memory tobe read or written. During a memory access, Port 0’s eight pins (AD0-AD7) first holdthe lower byte of the address, followed by the data to be read or written. This methodof carrying both addresses and data on the same signal lines is called a multiplexedaddress/data bus. It’s a popular arrangement that many devices use, since itrequires fewer pins on the chip, compared to giving each data and address line itsown pin. Port 2’s eight lines hold the higher byte of the address to be read or writtento. These lines make up the high address bus (A8-A15). Together, the 16 addresslines can access 64 kilobytes (65,536 bytes) of memory, from 00000000 00000000to 11111111 11111111 in binary, or 0000h to FFFFh in hexadecimal. Besides pinsto hold the data and addresses, the 8052 must also provide control signals to initiatethe read and write operations. Control signals include WR (write), RD (read), PSEN(program store enable), and ALE (address latch enable). Some of the address lines

Page 36: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (36)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

may also function as control signals that help to select a chip during a memoryaccess.

Code and data memory. To understand the operation of the control signals, youneed to know a little about how the 8052 distinguishes between two types ofmemory: data and code, or program, memory. By using different control signals foreach type of memory, the 8052 can access two separate 64K areas of memory, witheach addressed from 0000h to FFFFh, and each using the same data and addresslines. The 8052 accesses code memory when it executes an assembly-languageprogram or subroutine. Code memory is read-only; you can’t write to it. The onlyinstructions that access code memory are read operations. Code memory is intendedfor programs or subroutines that have been previously programmed into ROM orEPROM. The 8052 strobes, or pulses, PSEN when it accesses external codememory. Accesses to internal code memory (the BASIC-52 interpreter in ROM) donot use PSEN or any external control signals. Data memory is read/write memory,usually RAM. Instructions that read data memory strobe RD, and instructions thatwrite to data memory strobe WR. The termdata memory may be misleading,because it can hold any information that is accessed with instructions that strobe RDor WR. In fact, BASIC-52 programs are stored in data memory, not code memory asyou might think. This is because the 8052 does not execute the BASIC programsdirectly. Instead, the BASIC-52 interpreter program reads the BASIC programs asdata and then translates them to machine code for execution by the 8052. If youdon’t need all of the available memory space, you can combine code and datamemory in a single area. With combined memory, WR controls write operations, andPSEN and RD are logically ANDed to create a read signal that is active when eitherPSEN or RD is low. Combined data/code memory is handy if you want the flexibilityto store either BASIC or assembly-language programs in the same chip, or if youwant to be able to upload assembly-language routines into RAM for testing. ALE isthe final control signal for accessing external memory. It controls an external latchthat stores the lower address byte during memory accesses. When the 8052 readsor writes to external memory, it places the lower address byte on AD0-AD7 andstrobes ALE, which causes the external latch to save the lower address byte for therest of the read or write cycle. After a short delay, the 8052 replaces the address onAD0-AD7 with the data to be written or read.

Timers and Counters. The 8052 has three 16-bit timer/counters, which make it easyto generate periodic signals or count signal transitions. BASIC-52 assigns optionalfunctions for each of the timer/counters. Timer 0 controls a real-time clock thatincrements every 5 milliseconds. You can use this clock to time events that occur atregular intervals, or as the base for clock or calendar functions. Timer 1 has severaluses in BASIC-52, including controlling a pulse-width-modu-lated output (PWM) (aseries of pulses of programmable width and number); writing to a line Inside the8052-BASIC printer or other serial peripheral (LPT); and generating pulses forEPROM programming (PGM PULSE). Timer 2 generates a baud rate for serialcommunications at SER IN and SER OUT. These are all typical applications fortimer/counters in microcontroller circuits. If you don’t use the optional timer functions,you can program the timers for other applications. In addition to timing functions,

Page 37: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (37)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

where the timer increments at a defined rate, you can use the timers for eventcounting, where the timer increments on an external trigger and measures the timebetween triggers. If you use the timers for event counting, T2, T2(EX), T0, and T1detect transitions to be counted.

The serial port. The 8052’s serial port automatically takes care of many of thedetails of serial communications. On the transmit side, the serial port translatesbytes to be sent into serial data, including adding start and stop bits and writing thedata in a timed sequence to SER OUT. On the receive side, the serial port acceptsserial data at SER IN and sets a flag to indicate that a byte has been received.BASIC-52 uses the serial port for communicating with a host computer.

External interrupts. INT0 and INT1 are external interrupt inputs, which detect logiclevels or transitions that interrupt the CPU and cause it to branch to a predefinedprogram location. BASIC-52 uses INT0 for its optional direct-memory-access (DMA)function.

Programming functions. BASIC-52’s programming commands use three additionalport bits (ALEDIS, PGM PULSE, and PGM EN) to control programming voltages andtiming for storing BASIC-52 programs in EPROM or other nonvolatile memory.Additional Control Inputs Two additional control inputs need to be mentioned. A logichigh on RESET resets the chip and causes it to begin executing the program thatbegins at 0 in code memory. In the 8052-BASIC chip, this program is the BASIC-52interpreter. EA (external memory access) determines whether the chip will accessinternal or external code memory in the area from 0 to 1FFFh. In BASIC-52 systems,EA is tied high so that the chip runs the BASIC interpreter in internal ROM on boot-up.

Power Supply Connections And, finally, the chip has two pins for connecting toa +5-volt DC power supply (VCC) and ground (VSS). That finishes our tour of the8052-BASIC chip. We’re now ready to put together a working system.

Page 38: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (38)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

6. Special microcontroller features

Inside of a microcontroller are special function building blocks which makes thedifferent controllers the best choice for different applications. These specialfunctions could be:

Watchdog timerA watchdog timer provides a means of graceful recovery from a system problem.This could be a program that goes into an endless loop, or a hardware problem thatprevents the program from operating correctly. If the program fails to reset thewatchdog at some predetermined interval, a hardware reset will be initiated. Thebug may still exist, but at least the system has a way to recover. This is especiallyuseful for unattended systems.

Idle/Halt/WakeupThe device can be placed into IDLE/HALT mode by software control. In both Haltand Idle conditions the state of the microcontroller remains. RAM is not cleared andany outputs are not changed. The terms idle and halt often have different definitions,depending on the manufacturer.

In IDLE mode, all activities are stopped except:• associated on-board oscillator circuitry• watchdog logic (if any)• the clock monitor• the idle timer (a free running timer)

Power supply requirements on the microcontroller in this mode are typically around30% of normal power requirements of the microprocessor. Idle mode is exited by areset, or some other stimulus (such as timer interrupt, serial port, etc.). A specialtimer/counter (the idle timer) causes the chip to wake up at a regular interval tocheck if things are OK. The chip then goes back to sleep.

In Halt mode, all activities are stopped (including timers and counters). The onlyway to wake up is by a reset or device interrupt (such as an I/O port). The powerrequirements of the device are minimal and the applied voltage (Vcc) can sometimesbe decreased below operating voltage without altering the state (RAM/Outputs) ofthe device. Current consumption is typically less than 1 uA.

6.1. Peripheral I/O

UARTA UART (Universal Asynchronous Receiver Transmitter) is a serial port adapter forasynchronous serial communications.

Page 39: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (39)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

USARTA USART (Universal Synchronous/Asynchronous Receiver Transmitter) is a serialport adapter for either asynchronous or synchronous serial communications.Communications using a USART are typically much faster (as much as 16 times)than with a UART.

Synchronous serial portA synchronous serial port doesn't require start/stop bits and can operate at muchhigher clock rates than an asynchronous serial port. Used to communicate with highspeed devices such as memory servers, display drivers, additional A/D ports, etc.Can also be used to implement a simple microcontroller network.

Analog to Digital Conversion (ADC)Converts an external analog signal (typically relative to voltage) and converts it to adigital representation. Microcontrollers that have this feature can be used forinstrumentation, environmental data logging, or any application that lives in ananalog world.

Digital to Analog Converters (DAC)This feature takes a Digital number and converts it to a analog output. The number50 would be changed to the analog output of (50/256 * 5Volts) = .9765625V on a 8-bit / 5 Volt system.

Pulse width modulatorOften used as a digital-to-analog conversion technique. A pulse train is generatedand regulated with a low-pass filter to generate a voltage proportional to the dutycycle.

Pulse accumulatorA pulse accumulator is an event counter. Each pulse increments the pulseaccumulator register, recording the number of times this event has occurred.

I2C bus - Inter-Integrated Circuit bus (Philips)The I2C bus is a simple 2 wire serial interface developed by Philips. It wasdeveloped for 8 bit applications and is widely used in consumer electronics,automotive and industrial applications. In addition to microcontrollers, severalperipherals also exist that support the I2C bus.The I2C bus is a two line, multi-master, multi-slave network interface with collisiondetection. Up to 128 devices can exist on the network and they can be spread outover 10 meters. Each node (microcontroller or peripheral) may initiate a message,and then transmit or receive data. The two lines of the network consist of the serialdata line and the serial clock line. Each node on the network has a unique addresswhich accompanies any message passed between nodes. Since only 2 wires areneeded, it is easy to interconnect a number of devices.

CAN

Page 40: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (40)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

CAN (Controller Area Network) is a multiplexed wiring scheme that was developedjointly by Bosch and Intel for wiring in automobiles. The CAN specification seems tobe the one that is being used in industrial control both in North American andEurope. With lower cost microcontrollers that support CAN, CAN has a goodpotential to take off.

Page 41: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (41)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

6.2. Advanced Memory options

EEPROM - Electrically Erasable Programmable Read Only MemoryMany microcontrollers have limited amounts of EEPROM on the chip. EEPROMseems more suited (because of its economics) for small amounts of memory thathold a limited number of parameters that may have to be changed from time to time.This type of memory is relatively slow, and the number of erase/write cycles allowedin its lifetime is limited.

FLASH (EPROM)Flash provides a good better solution than regular EEPROM when there is arequirement for large amounts of non-volatile program memory. It is both faster andpermits more erase/write cycles than EEPROM.

Battery backed-up static RAMBattery backed-up static RAM is useful when a large non-volatile program and DATAspace is required. A major advantage of static RAM is that it is much faster thanother types of non-volatile memory so it is well suited for high performanceapplication. There also are no limits as to the number of times that it may bewritten to so it is perfect for applications that keep and manipulate large amounts ofdata locally.

OTP - One Time Programmable (PROM)An OTP is a PROM (Programmable Read-Only-Memory) device. Once yourprogram is written into the device with a standard EPROM programmer, it can not beerased or modified. This is usually used for limited production runs before a ROMmask is done in order to test code. A OTP (One Time Programmable) part usesstandard EPROM, but the package has no window for erasing.

Software protectionEither by encryption or fuse protection, the programmed software is protectedagainst unauthorized snooping (reverse engineering, modifications, piracy, etc.).

6.3. Power Management and Low Voltage

Low voltage partsIn the recent past, as consumer goods are beginning to drive major segments of themicrocontroller market, and as consumer goods become portable and lightweight,the requirement for 3 volt (and lower) microcontrollers has become urgent (3 volts =2 battery solution / lower voltage = longer battery life). Most low voltage parts in themarket today are simply 5 volt parts that were modified to operate at 3 volts (usuallyat a performance loss). Some micros being released now are designed from theground up to operate properly at 3.0 (and lower) voltages, which offer comparableperformance of the 5 volt devices.

Page 42: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (42)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

There are a few interesting rules of thumb regarding transistors:1) The amount of power they dissipate is proportional to their size. If you make

a transistor half as big, it dissipates half as much power.2) Their propagation delay is proportional to their size. If you make a transistor

half as big, it's twice as fast.3) Their cost is proportional to the square of their size. If you make them half as

big, they cost one quarter as much.

If you make a transistor smaller, you improve the power, speed, and cost. The onlydrawback is that they are harder to make. Everybody in the world wants to maketransistors smaller and smaller, the advantages are enormous.For years people have been using 5 Volts to power IC's. Because the transistorswere large, there was little danger damaging the transistor putting this voltageacross it. However, now that the transistors are getting so small, 5 Volts will actuallyfry them. The only way around this is to start lowering the voltage. This is whypeople are now using 3 (actually 3.3) Volt logic, and lower in the next few years. Itisn't just because of batteries.

Interrupts

PollingPolling is not really a "feature" - it's what you have to do if your microcontroller ofchoice does not have interrupts. Polling is a software technique whereby thecontroller continually asks a peripheral if it needs servicing. The peripheral sets aflag when it has data ready for transferring to the controller, which the controllernotices on its next poll. Several such peripherals can be polled in succession, withthe controller jumping to different software routines, depending on which flagshave been set.

InterruptsRather than have the microcontroller continually polling - that is, asking peripherals(timers / UARTS / A/Ds / external components) whether they have any data available(and finding most of the time they do not), a more efficient method is to have theperipherals tell the controller when they have data ready. The controller can becarrying out its normal function, only responding to peripherals when there is data torespond to. On receipt of an interrupt, the controller suspends its current operation,identifies the interrupting peripheral, then jumps (vectors) to the appropriate interruptservice routine.The advantage of interrupts, compared with polling, is the speed of response toexternal events and reduced software overhead (of continually asking peripherals ifthey have any data ready). Most microcontrollers have at least one externalinterrupt, which can be edge selectible (rising or falling) or level triggered. Bothsystems (edge/level) have advantages. Edge - is not time sensitive, but it issusceptible to glitches. Level - must be held high (or low) for a specific duration(which can be a pain - but is not susceptible to glitches).

Page 43: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (43)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

Page 44: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (44)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

7. Writing the Control Program

When it’s time to write the program that controls your project, the options includeusing machine code, assembly language, or a higher-level language. Whichprogramming languageyou use depends on things like desired execution speed, program length, andconvenience, as well as what’s available in your price range.

Machine code. The most fundamental program form is machine code, the binaryinstructions that cause the CPU to perform the operations you desire.

7.1. Assembly language. One step removed from machine code is assemblylanguage, where abbreviations called mnemonics (memory aids) substitute for themachine codes. The mnemonics are easier to remember than the machine codesthey stand for. For example, in the 8052’s assembly language, the mnemonic CLR Cmeans clear the carry bit, and is easier to remember than its binary code(11000011). Since machine code is ultimately the only language that a CPUunderstands, you need some way of translating assembly-language programs intomachine code. For very short programs, you can hand assemble, or translate themnemonics yourself by looking up the machine codes for each abbreviation. Anotheroption is to use an assembler, which is software that runs on a desktop computerand translates the mnemonics into machine code. Most assemblers provide otherfeatures, such as formatting the program code and creating a listingthat shows both the machine-code and assembly-language versions of a programside -by-side.

7.2. Higher-level languages. A disadvantage to assembly language is that eachdevice family has its own set of mnemonics, so you have to learn a new vocabularyfor each family you work with. To get around this problem, higher-level languageslike C, Pascal, Fortran, Forth, and BASIC follow a standard syntax so that programsare more portable from one device to another. The idea is that with minor changes,you can use a language like BASIC to write programs for many different devices. Inreality, each language tends to develop many different dialects, depending on thechip and the preferences of the language’s vendor, so porting a program to adifferent device isn’t always effortless. But there are many similarities among thedialects of a single language, so, as with spoken language, a new dialect is easier tolearn than a whole new language. Higher-level languages also simplify programmingby allowing you to do in one or a few lines what would require many lines ofassembly code to accomplish.

Interpreters and compilers are two forms of higher-level languages. An interpretertrans-lates program into machine code each time the program runs, while a compilertranslates nly once, creating a new, executable file that the computer runs directly,without re-trans-lating. As a rule, interpreters are very convenient for shorterprograms where execution speed isn’t critical. With an interpreted language, you canrun your program code immediately after you write it, without a separate compile or

Page 45: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (45)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

assembly step. A compiler is a good choice when a program is long or has toexecute quickly. A single language like BASIC may be availablein both interpreted and compiled versions. Each device family requires its owninterpreter or compiler to translate the higher-level code into the machine code forthat device. In other words, you can’t use QuickBASIC for IBM PCs to program an8052 microcontroller—you need a compiler that generates program code for the8052. Compared to an equivalent program written in assembly language, a compiledprogram usually is larger and slower, so assembly language is the way to go if aprogram must be as fast or as small as possible. A higher-level language also maynot offer all of the abilities of assembly code, though you can get around this bycalling subroutines in assembly language when necessary.

BASIC-52 is an interpreted language, but BASIC compilers for the 8052 are alsoavailable. In fact, you can have the best of both worlds by testing your programs withthe BASIC-52 interpreter, and compiling the finished product for faster execution andother benefits of the compiled version.

8. Testing and Debugging

After you’ve written a program, or a section of one, it’s time to test it and asnecessary, find and correct mistakes to get it working properly. The process offerreting out and correcting mistakes is called debugging. Easy debugging andtroubleshooting can make a big differencein how long it takes to get a system up and running. As with programming, you haveseveral options here as well.

8.1. Testing in EPROM. One way is to burn your program into EPROM, install theEPROM in your system, run the program, and observe the results. If problems occur(as they usually will) you modify the program, erase and reburn the EPROM, and tryagain, repeating as many times as necessary until the system is operating properly.

8.2. Development systems. Another option is to use a development system. Atypical development system consists of a monitor program, which is a programstored in EPROM or other memory in the microcontroller system, and a serial link toa personal computer. Using the abilities of the monitor program, you can load yourprogram from a personal computer into RAM (instead of the more permanentEPROM) on the microcontroller system, then run the program, modify it, and retry asoften as necessary until the program is working properly. Most development systemsalso allow single-stepping, setting breakpoints, and viewing and changing the data inmemory. In single-stepping, you run the program one step at time, pausing aftereach step, so you can more easily monitor what the circuits and program are doingat each step. A breakpoint is a program location where the program stops executingand waits for a command to continue. You can set breakpoints at critical spots inyour program. At any breakpoint, you can view or change the contents of memory orperform other tests.

Page 46: Introduction to MicroProcessors and MicroControllers · controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly

Microcontroller (46)

Heinz Rongen Forschungszentrum Jülich, ZEL 52425 Jülich, GermanyTel: +49-(0)2461-614512 Fax: +49-(0)2461-613990 Email: [email protected]

8.3. The 8052-BASIC’s development system

The 8052-BASIC system and a personal computer form a complete developmentsystem for writing, testing, and storing programs. The personal computer’s keyboardand screen make it easy to write and run programs and view the results. BASIC-52has many built-in debugging features that make it easy to test programs. You canrun a program immediately after writing it, without having to assemble, compile, orprogram an EPROM. You can use a STOP statement and CONT (continue)command to set breakpoints and resume executing your program. You can usePRINT statements to display variables as the program runs. And, if you wish, youcan use your personal computer for writing programs off-line and uploading anddownloading them to the 8052-BASIC system.