Feb 11, 2009

8051 instructions

  •  ACALL - Absolute Call
  •  ADD, ADDC - Add Accumulator (With Carry)
  •  AJMP - Absolute Jump
  •  ANL - Bitwise AND
  •  CJNE - Compare and Jump if Not Equal
  •  CLR - Clear Register
  •  CPL - Complement Register
  •  DA - Decimal Adjust
  •  DEC - Decrement Register
  •  DIV - Divide Accumulator by B
  •  DJNZ - Decrement Register and Jump if Not Zero
  •  INC - Increment Register
  •  JB - Jump if Bit Set
  •  JBC - Jump if Bit Set and Clear Bit
  •  JC - Jump if Carry Set
  •  JMP - Jump to Address
  •  JNB - Jump if Bit Not Set
  •  JNC - Jump if Carry Not Set
  •  JNZ - Jump if Accumulator Not Zero
  •  JZ - Jump if Accumulator Zero
  •  LCALL - Long Call
  •  LJMP - Long Jump
  •  MOV - Move Memory
  •  MOVC - Move Code Memory
  •  MOVX - Move Extended Memory
  •  MUL - Multiply Accumulator by B
  •  NOP - No Operation
  •  ORL - Bitwise OR
  •  POP - Pop Value From Stack
  •  PUSH - Push Value Onto Stack
  •  RET - Return From Subroutine
  •  RETI - Return From Interrupt
  •  RL - Rotate Accumulator Left
  •  RLC - Rotate Accumulator Left Through Carry
  •  RR - Rotate Accumulator Right
  •  RRC - Rotate Accumulator Right Through Carry
  •  SETB - Set Bit
  •  SJMP - Short Jump
  •  SUBB - Subtract From Accumulator With Borrow
  •  SWAP - Swap Accumulator Nibbles
  •  XCH - Exchange Bytes
  •  XCHD - Exchange Digits
  •  XRL - Bitwise Exclusive OR
  •  Undefined - Undefined Instruction

The Microcontroller

A microcontroller (also MCU or µC) is a functional computer system-on-a-chip. It contains a processor core, memory, and programmable input/output peripherals.

Microcontrollers include an integrated CPU, memory (a small amount of RAM, program memory, or both) and peripherals capable of input and output.

It emphasizes high integration, in contrast to a microprocessor which only contains a CPU (the kind used in a PC). In addition to the usual arithmetic and logic elements of a general purpose microprocessor, the microcontroller integrates additional elements such as read-write memory for data storage, read-only memory for program storage, Flash memory for permanent data storage, peripherals, and input/output interfaces. Microcontrollers often operate at very low speed compared to microprocessors (at clock speeds of as little as 32KHz), but this is adequate for typical applications. They consume relatively little power (milliwatts or even microwatts), and will generally have the ability to retain functionality while waiting for an event such as a button press or interrupt. Power consumption while sleeping (CPU clock and peripherals disabled) may be just nanowatts, making them ideal for low power and long lasting battery applications.

Microcontrollers are used in automatically controlled products and devices, such as automobile engine control systems, remote controls, office machines, appliances, power tools, and toys. By reducing the size, cost, and power consumption compared to a design using a separate microprocessor, memory, and input/output devices, microcontrollers make it economical to electronically control many more processes.

Embedded design

The majority of computer systems in use today are embedded in other machinery, such as automobiles, telephones, appliances, and peripherals for computer systems. These are called embedded systems. While some embedded systems are very sophisticated, many have minimal requirements for memory and program length, with no operating system, and low software complexity. Typical input and output devices include switches, relays, solenoids, LEDs, small or custom LCD displays, radio frequency devices, and sensors for data such as temperature, humidity, light level etc. Embedded systems usually have no keyboard, screen, disks, printers, or other recognizable I/O devices of a personal computer, and may lack human interaction devices of any kind.

Interrupts

It is mandatory that microcontrollers provide real time response to events in the embedded system they are controlling. When certain events occur, an interrupt system can signal the processor to suspend processing the current instruction sequence and to begin an interrupt service routine (ISR). The ISR will perform any processing required based on the source of the interrupt before returning to the original instruction sequence. Possible interrupt sources are device dependent, and often include events such as an internal timer overflow, completing an analog to digital conversion, a logic level change on an input such as from a button being pressed, and data received on a communication link. Where power consumption is important as in battery operated devices, interrupts may also wake a microcontroller from a low power sleep state where the processor is halted until required to do something by a peripheral event.

Programs

Microcontroller programs must fit in the available on-chip program memory, since it would be costly to provide a system with external, expandable, memory. Compilers and assembly language are used to turn high-level language programs into a compact machine code for storage in the microcontroller's memory. Depending on the device, the program memory may be permanent, read-only memory that can only be programmed at the factory, or program memory may be field-alterable flash or erasable read-only memory.

Other microcontroller features

Since embedded processors are usually used to control devices, they sometimes need to accept input from the device they are controlling. This is the purpose of the analog to digital converter. Since processors are built to interpret and process digital data, i.e. 1s and 0s, they won't be able to do anything with the analog signals that may be being sent to it by a device. So the analog to digital converter is used to convert the incoming data into a form that the processor can recognize. There is also a digital to analog converter that allows the processor to send data to the device it is controlling.

In addition to the converters, many embedded microprocessors include a variety of timers as well. One of the most common types of timers is the Programmable Interval Timer, or PIT for short. A PIT just counts down from some value to zero. Once it reaches zero, it sends an interrupt to the processor indicating that it has finished counting. This is useful for devices such as thermostats, which periodically test the temperature around them to see if they need to turn the air conditioner on, the heater on, etc.

Time Processing Unit or TPU for short. Is essentially just another timer, but more sophisticated. In addition to counting down, the TPU can detect input events, generate output events, and other useful operations.

Dedicated Pulse Width Modulation (PWM) block makes it possible for the CPU to control power converters, resistive loads, motors, etc., without using lots of CPU resources in tight timer loops.

Universal Asynchronous Receiver/Transmitter (UART) block makes it possible to receive and transmit data over a serial line with very little load on the CPU.

For those wanting ethernet one can use an external chip like Crystal Semiconductor CS8900A, Realtek RTL8019, or Microchip ENC 28J60. All of them allow easy interfacing with low pin count.

Higher integration

In contrast to general-purpose CPUs, microcontrollers may not implement an external address or data bus as they integrate RAM and non-volatile memory on the same chip as the CPU. Using fewer pins, the chip can be placed in a much smaller, cheaper package.

Integrating the memory and other peripherals on a single chip and testing them as a unit increases the cost of that chip, but often results in decreased net cost of the embedded system as a whole. Even if the cost of a CPU that has integrated peripherals is slightly more than the cost of a CPU + external peripherals, having fewer chips typically allows a smaller and cheaper circuit board, and reduces the labor required to assemble and test the circuit board.

A microcontroller is a single integrated circuit, commonly with the following features:

  • central processing unit - ranging from small and simple 4-bit processors to complex 32- or 64-bit processors
  • discrete input and output bits, allowing control or detection of the logic state of an individual package pin
  • serial input/output such as serial ports (UARTs)
  • other serial communications interfaces like I²C, Serial Peripheral Interface and Controller Area Network for system interconnect
  • peripherals such as timers, event counters, PWM generators, and watchdog
  • volatile memory (RAM) for data storage
  • ROM, EPROM, EEPROM or Flash memory for program and operating parameter storage
  • clock generator - often an oscillator for a quartz timing crystal, resonator or RC circuit
  • many include analog-to-digital converters
  • in-circuit programming and debugging support

This integration drastically reduces the number of chips and the amount of wiring and circuit board space that would be needed to produce equivalent systems using separate chips. Furthermore, and on low pin count devices in particular, each pin may interface to several internal peripherals, with the pin function selected by software. This allows a part to be used in a wider variety of applications than if pins had dedicated functions. Microcontrollers have proved to be highly popular in embedded systems since their introduction in the 1970s.

Some microcontrollers use a Harvard architecture: separate memory buses for instructions and data, allowing accesses to take place concurrently. Where a Harvard architecture is used, instruction words for the processor may be a different bit size than the length of internal memory and registers; for example: 12-bit instructions used with 8-bit data registers.

The decision of which peripheral to integrate is often difficult. The microcontroller vendors often trade operating frequencies and system design flexibility against time-to-market requirements from their customers and overall lower system cost. Manufacturers have to balance the need to minimize the chip size against additional functionality.

Microcontroller architectures vary widely. Some designs include general-purpose microprocessor cores, with one or more ROM, RAM, or I/O functions integrated onto the package. Other designs are purpose built for control applications. A microcontroller instruction set usually has many instructions intended for bit-wise operations to make control programs more compact. For example, a general purpose processor might require several instructions to test a bit in a register and branch if the bit is set, where a microcontroller could have a single instruction that would provide that commonly-required function.

Microcontrollers typically do not have a math coprocessor, so floating point multiplication and division are carried out using a standard library, or the faster and more compact Horner method.

Volumes

About 55% of all CPUs sold in the world are 8-bit microcontrollers. According to Semico, Over 4 billion 8-bit microcontrollers were sold in 2006

A typical home in a developed country is likely to have only four general-purpose microprocessors but around three dozen microcontrollers. A typical mid range automobile has as many as 30 or more microcontrollers. They can also be found in any electrical device: washing machines, microwave ovens, telephones etc.

clip_image001[4]

clip_image002[4]

A PIC 18F8720 microcontroller in an 80-pin TQFP package.

Manufacturers have often produced special versions of their microcontrollers in order to help the hardware and software development of the target system. Originally these included EPROM versions that have a "window" on the top of the device through which program memory can be erased by ultra violet light, ready for reprogramming after a programming ("burn") and test cycle. Since 1998, EPROM versions are rare and have been replaced by EEPROM and flash, which are easier to use (can be erased electronically) and cheaper to manufacture.

Other versions may be available where the ROM is accessed as an external device rather than as internal memory, however these are becoming increasingly rare due to the widespread availability of cheap microcontroller programmers.

The use of field-programmable devices on a microcontroller may allow field update of the firmware or permit late factory revisions to products that have been assembled but not yet shipped. Programmable memory also reduces the lead time required for deployment of a new product.

Where hundreds of thousands of identical devices are required, using parts programmed at the time of manufacture can be an economical option. These 'Mask Programmed' parts have the program laid down in the same way as the logic of the chip, at the same time.

Programming environments

Microcontrollers were originally programmed only in assembly language, but various high-level programming languages are now also in common use to target microcontrollers. These languages are either designed specially for the purpose, or versions of general purpose languages such as the C programming language. Compilers for general purpose languages will typically have some restrictions as well as enhancements to better support the unique characteristics of microcontrollers. Some microcontrollers have environments to aid developing certain types of applications. Microcontroller vendors often make tools freely available to make it easier to adopt their hardware.

Many microcontrollers are so quirky that they effectively require their own non-standard dialects of C, such as SDCC for the 8051, which prevent using standard tools (such as code libraries or static analysis tools) even for code unrelated to hardware features. Interpreters are often used to hide such low level quirks.

Interpreter firmware is also available for some microcontrollers. For example, BASIC on the early microcontrollers Intel 8052[4]; BASIC and FORTH on the Zilog Z8 as well as some modern devices. Typically these interpreters support interactive programming.

Simulators are available for some microcontrollers, such as in Microchip's MPLAB environment. These allow a developer to analyse what the behaviour of the microcontroller and their program should be if they were using the actual part. A simulator will show the internal processor state and also that of the outputs, as well as allowing input signals to be generated. While on the one hand most simulators will be limited from being unable to simulate much other hardware in a system, they can exercise conditions that may otherwise be hard to reproduce at will in the physical implementation, and can be the quickest way to debug and analyse problems.

Recent microcontrollers are often integrated with on-chip debug circuitry that when accessed by an In-circuit emulator via JTAG, allow debugging of the firmware with a debugger.

Interrupt latency

In contrast to general-purpose computers, microcontrollers used in embedded systems often seek to minimize interrupt latency over instruction throughput.

When an electronic device causes an interrupt, the intermediate results, the registers, have to be saved before the software responsible for handling the interrupt can run, and then must be put back after it is finished. If there are more registers, this saving and restoring process takes more time, increasing the latency.

Low-latency MCUs generally have relatively few registers in their central processing units, or they have "shadow registers", a duplicate register set that is only used by the interrupt software.

History

The first single chip microprocessor was the 4 bit Intel 4004 released in 1971, with other more capable processors available over the next several years.

These however all required external chip(s) to implement a working system, raising total system cost, and making it impossible to economically computerise appliances.

The first computer system on a chip optimised for control applications - microcontroller was the Intel 8048 released in 1975[citation needed], with both RAM and ROM on the same chip. This chip went on to be found in over a billion PC keyboards, and numerous applications.

Most microcontrollers at this time had two variants. One had an erasable EEPROM program memory, which was significantly more expensive than the PROM variant which was only programmable once.

In 1993, the introduction of EEPROM memory allowed microcontrollers (beginning with the Microchip PIC16x84) to be electrically erased quickly without an expensive package as required for EPROM, allowing both rapid prototyping, and In System Programming.

The same year, Atmel introduced the first microcontroller using Flash memory.

Other companies rapidly followed suit, with both memory types.

Cost has plummeted over time, with the cheapest microcontrollers being available for well under $0.25 in 2009 , and 32 bit microcontrollers under $5.

Nowadays microcontrollers are low cost and readily available for hobbyists, with large online communities around certain processors.

Feb 7, 2009

Inside the 8052-BASIC

Inside the 8052-BASIC

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

The 8052-BASIC microcontroller is an easy-to-use, low-cost, and versatile computer-on-achip.
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, and disk drives. If you’re
interested in doing more with computers than simply running applications programs, the
8052-BASIC gives you a chance to design and build a system from the ground up.
With a few support chips and a program stored in memory, you can use the 8052-BASIC to
sense, measure, and control processes, events, or conditions. Here are just a few examples
of the uses you can put it to:
· data collection
·machine control
· test equipment
· wired and wireless links for communications and control

The 8052-BASIC is actually two products in one: it’s an 8052 microcontroller, with the
BASIC-52 programming language on-chip. To begin using the 8052-BASIC, you need a
minimum circuit consisting of the 8052-BASIC and some support components, plus a
personal computer. This book contains specific instructions for use with “IBM-compatible,”
or MS-DOS, computers, but you can use any computer that has an RS-232 serial port and
communications software to go with it. Figure 2-1 shows the basic setup.

With an 8052-BASIC circuit connected by a serial link to a personal computer, you have 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 and commands
that the 8052-BASIC system executes. BASIC-52 is an interpreted language whose
programs do not require an additional assembling or compiling step. You can run
programs or execute commands immediately after you write them.
·
You can use BASIC-52’s programming functions to permanently store your programs
in EPROM or other nonvolatile memory. You don’t need a separate EPROM
programmer.
· You can also store programs on your personal computer’s disk. You can write or edit
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 other
components, depending on the needs of your project.
· After program development, you can disconnect the link to the personal computer and
let the 8052-BASIC system run its stored program on its own.

Limits
No single product is ideal for every use. These are some of the limitations to the 8052-BASIC:
· Program execution can be slow, compared with programs that run on more powerful
computers, or programs written in assembly language. A typical program line in
BASIC-52 takes several milliseconds to execute. Because of this, there are some tasks
that BASIC-52 just can’t handle—for example, detecting and responding to an interrupt
within a few microseconds. But for many control, monitoring, and other tasks,
BASIC-52 is fine. For example, a weather station that senses conditions once per
minute and stores or displays the results doesn’t need super-fast response. And, if
necessary, you can call an assembly-language routine for a portion of a program where
speed is critical.

Even if you write your programs in assembly language, C, or another language, you can
use the 8052-BASIC system as a development system that enables you to upload your
program to memory, run the program, and test and debug your programs and circuits.

· Another limitation of the 8052-BASIC is that a complete project requires additional
components. If you’re looking for a true single-chip solution, the 8052-BASIC isn’t it.
Even a minimal system requires an external RAM chip, and most systems also have an
external EPROM or other non-volatile memory. The serial link and other optional
functions also use some of the on-chip timers and input/output ports, so these may not
be available for other uses.

Still, the 8052-BASIC lets you to do a lot with a little. When needed, you can easily add
chips to expand the input/output ports, timers, and other functions.

·And finally, don’t expect BASIC-52 to have the abilities of QBasic, Visual Basic or
other BASIC programming languages that you may use on your personal computer.
BASIC-52 is more capable than many other single-chip BASICs. It includes features
like loops, subroutines, string handling, and even floating-point math for handling
fractional quantities. But there are some primitive aspects to the language. For example,
the on-line editing functions are limited. Once you write a program line, you can
change it only by retyping from the beginning. The limitations are understandable,
because the entire programming language has to fit in the 8052’s 8 kilobytes of ROM.
Fancy editing and other features just aren’t feasible in this small space.

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

What You Need

To use the 8052-BASIC chip, you need the following equipment, materials, and skills:

Components
The 8052-BASIC chip and supporting components are widely available. Appendix A lists
sources for the components used in the circuits described in this book.

Power Supply

You’ll need a regulated +5-volt power supply to power the circuits. Output capability of at
least 500 milliamperes is recommended for general experimenting. The power supply can
be powered by batteries or AC line voltage, but it must have a regulated output between 4.75
and 5.25 volts.

Construction Materials

To build the circuits, you’ll need circuit-construction materials and the skills to use them.
Wire-wrapping is an effective, quick way to build the circuits described, but if you prefer,
you can use point-to-point soldering or design and make a printed-circuit board, or use any
method that you’re comfortable with. Another option is to buy one of the available kits or
prebuilt 8052-BASIC boards. You can then use this book as a guide to using and expanding
the abilities of your board. Appendix A lists board suppliers and books on project-construction
techniques.

Documentation

Using just the information in this book, you can build and begin using your system. For
serious experimenting, two additional references are recommended: programming and
hardware manuals. For programming, you have two choices: Intel’s BASIC-52 User’s
Manual, or Systronix’s BASIC-52 Programming. Each of these describes the BASIC-52
programming language in detail. The Intel manual includes a few schematics, while
Systronix’s version has more programming examples and is better organized in general.
Intel’s Embedded Microcontrollers data book is a hardware reference that describes the 8052
chip, including electrical specifications and timing requirements. It also includes an assembly-
language reference. Appendix A tells where to get these.

Other useful documentation includes data sheets for the other components in your projects.
For a small charge, many component vendors will send along data sheets for the parts you
order.

Host Computer

To program the 8052-BASIC, you connect its circuits to a host computer, using an RS-232
asynchronous serial port and terminal-emulation software. The computer can be any type,
as long as it has a serial port and appropriate software.

The serial port is the same connector where you plug in an external modem, serial printer,
serial mouse, or other RS-232 serial device.

Terminal-emulation software is the same type of software that you may use for modem
communications with an on-line BBS. Examples for MS-DOS computers are Datastorm
Technologies’ Procomm Plus and the Terminal accessory in Microsoft Windows. At minimum,
the software must enable you to do the following: set the baud rate and other
communications parameters, serially transmit the characters that you type at the keyboard,
and display the characters received at the serial port. Also useful, but not essential, is the
ability to upload and download text files from your disk, over the serial link. If you don’t
have a favorite communications program, look in shareware catalogs or the file areas of
online services or BBS’s, where you can try out the offerings for a small disk-copying or
downloading charge.

Test Equipment
Some basic test equipment will help you monitor, test, and troubleshoot your circuits.
Minimum requirements include a multimeter capable of reading volts, ohms, and milliamperes.
Just about any basic meter will do for this. A logic probe is convenient, but not
essential, for monitoring logic levels and transitions. Best of all, an oscilloscope lets you
view the actual waveforms on one or more channels.

Knowledge

This book assumes that you have a basic knowledge of electronic circuits, including digital
logic. It does not assume that you know a lot about computer programming and computer
circuits. Appendix A lists some books that cover the basics, if you want to review or learn
these. Appendix C is a review of hexadecimal, binary, and decimal number systems.

The 8051 Family

At the core of the 8052-BASIC is an 8052 microcontroller, a member of the 8051
microcontroller family. Intel Corporation introduced the 8051 in 1980. Since that time,
8051-family chips have been used as the base of thousands of products. Many other
companies, including Philips, Siemens, Dallas Semiconductor, OKI, Fujitsu, and Harris-
Matra now also make 8051-family chips. Some companies have expanded the 8051 family
by offering compatible chips with additional features.

Table 2-1 summarizes the differences among popular 8051-family chips. The 8052 is an
enhanced 8051, with an extra timer and more RAM and ROM. The 8031 and 8032 are
identical to the 8051 and 8052, except that the ROM area is unused, and program code must
be stored in an external EPROM or other memory chip.

The 8052, like other 8051-family chips, is available in NMOS and CMOS versions. Figure
2-2 shows the pinout of the 8052 and 8052-BASIC, and Table 2-2 describes the pin
functions.


Elements of the 8052 and 8052-BASIC

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

CPU

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

ROM

ROM (read-only memory) is the read-only memory that is programmed into the chip in the
manufacturing process. In the 8052-BASIC, the ROM contains the BASIC-52 interpreter
program that the 8052 executes on boot-up. As far as the hardware is concerned, this is the
only difference between the ordinary 8052 and the 8052-BASIC.
Figure 2-2 Pin functions of the 8052 and 8052-BASIC microcontrollers.


RAM

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

I/O Ports

I/O (Input/Output) Ports enable the 8052 to read and write to external memory and other
components. The 8052 has four 8-bit I/O ports (Ports 0-3). As the name 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 external memory, using the on-chip timer/counters,
detecting external interrupts, and handling serial communications. BASIC-52 assigns
alternate functions to the remaining port bits. Some of these functions are required by
BASIC-52, while others are optional. If you don’t use an alternate function, you can use the
bit for any control, monitoring, or other purpose in your application.

Accessing external memory: The largest alternate use of the ports has to do with accessing
external memory. Although the 8052 is a single-chip computer, a complete 8052-BASIC
system requires additional components. It must have external RAM 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 external memory. Data here
refers to a byte to be read or written, and may be any type of information, including program
code. The address defines the location in memory to be read or written.

During a memory access, Port 0’s eight pins (AD0-AD7) first hold the lower byte of the
address, followed by the data to be read or written. This method of carrying both addresses
and data on the same signal lines is called a multiplexed address/data bus. It’s a popular
arrangement that many devices use, since it requires fewer pins on the chip, compared to
giving each data and address line its own pin. Port 2’s eight lines hold the higher byte of the
address to be read or written to. These lines make up the high address bus (A8-A15). Together,
the 16 address lines can access 64 kilobytes (65,536 bytes) of memory, from 00000000
00000000 to 11111111 11111111 in binary, or 0000h to FFFFh in hexadecimal.

Besides pins to hold the data and addresses, the 8052 must also provide control signals to
initiate the 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 may also
function as control signals that help to select a chip during a memory access.

Code and data memory: To understand the operation of the control signals, you need to
know a little about how the 8052 distinguishes between two types of memory: data and code,
or program, memory. By using different control signals for each type of memory, the 8052
can access two separate 64K areas of memory, with each addressed from 0000h to FFFFh,
and each using the same data and address lines.

The 8052 accesses code memory when it executes an assembly-language program or
subroutine. Code memory is read-only; you can’t write to it. The only instructions that access
code memory are read operations. Code memory is intended for programs or subroutines
that have been previously programmed into ROM or EPROM. The 8052 strobes, or pulses,
PSEN when it accesses external code memory. Accesses to internal code memory (the
BASIC-52 interpreter in ROM) do not use PSEN or any external control signals.

Data memory is read/write memory, usually RAM. Instructions that read data memory strobe
RD, and instructions that write to data memory strobe WR. The termdata memory may be
misleading, because it can hold any information that is accessed with instructions that strobe
RD or WR. In fact, BASIC-52 programs are stored in data memory, not code memory as you
might think. This is because the 8052 does not execute the BASIC programs directly. Instead,
the BASIC-52 interpreter program reads the BASIC programs as data and then translates
them to machine code for execution by the 8052.

If you don’t need all of the available memory space, you can combine code and data memory
in a single area. With combined memory, WR controls write operations, and PSEN and RD
are logically ANDed to create a read signal that is active when either PSEN or RD is low.
Combined data/code memory is handy if you want the flexibility to store either BASIC or
assembly-language programs in the same chip, or if you want to be able to upload
assembly-language routines into RAM for testing.

ALE is the final control signal for accessing external memory. It controls an external latch
that stores the lower address byte during memory accesses. When the 8052 reads or writes
to external memory, it places the lower address byte on AD0-AD7 and strobes ALE, which
causes the external latch to save the lower address byte for the rest of the read or write cycle.
After a short delay, the 8052 replaces the address on AD0-AD7 with the data to be written or
read.

Timers and Counters: The 8052 has three 16-bit timer/counters, which make it easy to
generate periodic signals or count signal transitions. BASIC-52 assigns optional functions
for each of the timer/counters.

Timer 0 controls a real-time clock that increments every 5 milliseconds. You can use this
clock to time events that occur at regular intervals, or as the base for clock or calendar
functions. Timer 1 has several uses in BASIC-52, including controlling a pulse-width-modulated
output (PWM) (a series of pulses of programmable width and number); writing to a line
printer or other serial peripheral (LPT); and generating pulses for EPROM programming
(PGM PULSE). Timer 2 generates a baud rate for serial communications at SER IN and SER
OUT. These are all typical applications for timer/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, where the timer increments at a defined rate,
you can use the timers for event counting, where the timer increments on an external trigger
and measures the time between triggers. If you use the timers for event counting, T2, T2(EX),
T0, and T1 detect transitions to be counted.

The serial port: The 8052’s serial port automatically takes care of many of the details of
serial communications. On the transmit side, the serial port translates bytes to be sent into
serial data, including adding start and stop bits and writing the data in a timed sequence to
SER OUT. On the receive side, the serial port accepts serial 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 logic levels
or transitions that interrupt the CPU and cause it to branch to a predefined program location.
BASIC-52 uses INT0 for its optional direct-memory-access (DMA) function.

Programming functions: BASIC-52’s programming commands use three additional port
bits (ALEDIS, PGM PULSE, and PGM EN) to control programming voltages and timing for
storing BASIC-52 programs in EPROM or other nonvolatile memory.
Additional Control Inputs

Two additional control inputs need to be mentioned. A logic high on RESET resets the chip
and causes it to begin executing the program that begins at 0 in code memory. In the
8052-BASIC chip, this program is the BASIC-52 interpreter. EA (external memory access)
determines whether the chip will access internal 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 to a +5-volt DC power supply (VCC) and
ground (VSS).
That finishes our tour of the 8052-BASIC chip. We’re now ready to put together a working
system.

Microcontroller Basics

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 a microcontroller
project.

What’s a Microcontroller?
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 might be used to
control objects, processes, or events. Another term to describe a microcontroller is embedded
controller, because the microcontroller and its support circuits are often built into, or
embedded in, the devices they control.

You can find microcontrollers in all kinds of things these days. Any device that measures,
stores, controls, calculates, or displays information is a candidate for putting a microcontroller
inside. The largest single use for microcontrollers is in automobiles—just about every
car manufactured today includes at least one microcontroller for engine control, and often
more to control additional systems in the car. In desktop computers, you can find microcontrollers
inside keyboards, modems, printers, and other peripherals. In test equipment,
microcontrollers make it easy to add features such as the ability to store measurements, to
create and store user routines, and to display messages and waveforms. Consumer products
that use microcontrollers include cameras, video recorders, compact-disk players, and
ovens. And these are just 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’s Z80. Both microprocessors
and microcontrollers contain a central processing unit, or CPU. The CPU executes
instructions that perform the basic logic, math, and data-moving functions of a computer.
To make a complete computer, a microprocessor requires memory for storing data and
programs, and input/output (I/O) interfaces for connecting external devices like keyboards
and displays.

In contrast, a microcontroller is a single-chip computer because it contains memory and I/O
interfaces in addition to the CPU. Because the amount of memory and interfaces that can fit
on a single chip is limited, microcontrollers tend to be used in smaller systems that require
little more than the microcontroller and a few support components. Examples of popular
microcontrollers are Intel’s 8052 (including the 8052-BASIC, which is the focus of this
book), Motorola’s 68HC11, and Zilog’s Z8.

A Little History

To understand how microcontrollers fit into the always-expanding world of computers, we
need to look back to the roots of microcomputing.

In its January 1975 issue, Popular Electronics magazine featured an article describing the
Altair 8800 computer, which was the first microcomputer that hobbyists could build and
program themselves. The basic Altair included no keyboard, video display, disk drives, or
other elements we now think of as essential elements of a personal computer. Its 8080
microprocessor was programmed by flipping toggle switches on the front panel. Standard
RAM was 256 bytes and a kit version cost $397 ($498 assembled). A breakthrough in the
Altair’s usability occurred when a small company called Microsoft offered a version of the
BASIC programming language for it.

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 personal computer
now includes a keyboard, video display, disk drives, and Megabytes of RAM. What’s more,
there’s no longer any need to build a personal computer from scratch, since mass production
has drastically lowered the price of assembled systems. At most, building a personal
computer now involves only installing assembled boards and other major components in an
enclosure.

A personal computer like Apple’s Macintosh or IBM’s PC is a general-purpose machine,
since you can use it for many applications—word processing, spreadsheets, computer-aided
design, and more—just by loading the appropriate software from disk into memory.
Interfaces to personal computers are for the most part standard ones like those to video
displays, keyboards, and printers.

But along with cheap, powerful, and versatile personal computers has developed a new
interest in small, customized computers for specific uses. Each of these small computers is
dedicated to one task, or a set of closely related tasks. Adding computer power to a device
can enable it to do more, or do it faster, better, or more cheaply. For example, automobile
engine controllers have helped to reduce harmful exhaust emissions. And microcontrollers
inside computer modems have made it easy to add features and abilities beyond the basic
computer-to-phone-line interface.

In addition to their use in mass-produced products like these, it’s also become feasible to
design computer power into one-of-a-kind projects, such as an environmental controller for
a scientific study or an intelligent test fixture that ensures that a product meets its specifications
before it’s shipped to a customer.

At the core of many of these specialized computers is a microcontroller. The computer’s
program is typically stored permanently in semiconductor memory such as ROM or
EPROM. The interfaces between the microcontroller and the outside world vary with the
application, and may include a small display, a keypad or switches, sensors, relays, motors,
and so on.

These small, special-purpose computers are sometimes called 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 of computer systems, such as laptop and notebook
computers, are now manufactured on a single board.

New Tools

To design and build a computer-controlled device, you need skills in both circuit design and
software programming. The good news is that a couple of recent advances have simplified
the tasks involved.

One is the introduction of microcontrollers themselves, since they contain all of the elements
of a computer on a single chip. Using a microcontroller can reduce the number of
components and thus the amount of design work and wiring required for a project. The
8052-BASIC microcontroller even includes its own programming language, called BASIC-
52.

The other development is personal computers themselves. A desktop computer can help
tremendously by serving as a host system for writing and testing programs. As you are
developing a project, you can use a serial link to connect the host system to a target system,
which contains the microcontroller circuits you are testing. You can then use the personal
computer’s keyboard, video display, disk drives, and other resources for writing and testing
programs and transferring files between the two systems.

Project Steps
Putting together a microcontroller project involves several steps:
1. Define the task
2. Design and build the circuits
3. Write the control program
4. Test and debug

Sometimes the steps won’t follow exactly in this order. You may begin writing your program
before you build the circuits, or you may build and test some of the circuits before you start
programming. But however you go about it, each of the above steps is part of the process.
To see what’s involved in each step, let’s look at each in more detail.

Defining the Task

Every project begins with an idea, or a problem that needs a solution. For example, How
can I monitor light intensity at different locations and times of day to find the best location
for a solar collector? Or how can I automate the process of drilling printed-circuit boards?
Or how can I create a computer-controlled, animated display for a store window?
Once you know what you want to accomplish, you need to determine whether or not your
idea is one that requires a computer at all. In general, a computer is the way to go when the
circuits must make complex decisions or deal with complex data. For example, a simple
AND gate can easily decide whether or not two inputs are both valid logic highs, and will
change its output accordingly. But it would require many small-scale chips to build a circuit
that stores a series of values representing sensor outputs and the times they occurred, and
displays the information in an easily understandable form.

This type of application is where microcontrollers come in handy. Inside, microcontrollers
are little more than a carefully designed array of logic gates and memory cells, but modern
fabrication processes allow thousands of these to fit on a single chip. Since the basic
functions of a microcontroller—performing arithmetic, logic, data-moving, and program
branching functions—are common ones that are useful in many applications, it’s practical
to design and market a chip that performs these functions. The user accesses the abilities of
the microcontroller by writing a program that performs the desired functions.

On the other end of the scale, how do you know if an idea is suitable for a microcontroller,
or whether you should use a full desktop computer? If your design requires users to enter
or view complex commands, data, or graphical information, or if you need large amounts
of data or program storage, then a system with keyboard, full-screen display, and disk drives
makes sense. For simpler designs, a microcontroller with perhaps a keypad, small display,
and solid-state memory (no disk drives) can often do the job, with less expense and smaller
size.

In fact, recently the two extremes have been meeting. Some 32-bit microcontrollers are as
capable as desktop systems, and notebook-size computers are available with solid-state,
diskless storage. Also, expansion cards, other hardware, and software are now available for
those who want to use desktop computers for monitoring and control tasks. So there’s
something for everyone.

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 good way to
learn about microcontrollers and computers in general. Although you can’t do the most
complex projects with it, you can do a lot, at low cost and without a lot of hassle.

Designing and Building

When you’re ready to design and build the circuits for a project, there are several ways to
proceed. You can design your circuits from scratch, using manufacturers’ data books as
guides; you can follow a tested design (a kit or project presented in a magazine for example);
or you can buy an assembled single-board computer, adding only the interfaces and
programming your application requires. This book presents designs that you can build
yourself, but you can also use a kit or assembled board as a base if you wish.

Choosing a chip. Does it matter which microcontroller chip you use? All microcontrollers
contain a CPU, 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, each with
different combinations of options. For example, the 8052-BASIC is a member of the 8051
family of microcontrollers, which includes chips with program memory in ROM or EPROM,
and with varying amounts of RAM and other features. You select the version that best suits
your system’s requirements.

Microcontrollers are also characterized by how many bits of data they process at once, with
a higher number of bits generally indicating a faster or more powerful chip. Eight-bit chips
are popular for simpler designs, but 4-bit, 16-bit, and 32-bit architectures are also available.
The 8052-BASIC is an 8-bit chip.

Power consumption is another consideration, especially for battery-powered systems. Chips
manufactured with CMOS processes usually have lower power consumption than those
manufactured with NMOS processes. Many CMOS devices have special standby or “sleep”
modes that limit current consumption to as low as a few microamperes when the circuits are
inactive. Using these modes, a data logger can reduce its power consumption between
samples, and power up only when it’s time to take 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 term for its NMOS
process is HMOS.) Although Intel never offered a CMOS version directly, Micromint
became a source by ordering a batch of CMOS 8052’s with the BASIC-52 programming
language in ROM. The CMOS version, the 80C52-BASIC, has maximum power consumption
of 30 milliamperes, compared to 175 milliamperes for the NMOS 8052-BASIC.

All microcontrollers have a defined instruction set, which consists of the binary words that
cause the CPU to carry out specific operations. For example, 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 often require reading or changing single bits of input or output, rather than
reading and writing a byte at a time. For example, a microcontroller might use the eight bits
of an output port to switch power to eight sockets. If each socket must operate independently
of the others, a way is needed to change each bit without affecting the others. Many
microcontrollers include bit-manipulation (also called Boolean) opcodes that easily allow
programs to set, clear, compare, copy, or perform other logic operations on single bits of
data, rather than a byte at a time.

Options for storing programs. Another consideration in circuit design is how to store
programs. Instead of using disk storage, most microcontroller circuits store their programs
on-chip. For one-of-kind projects or small-volume production, EPROM has long been the
most popular method of program storage. Besides EPROMs, other options include
EEPROM, ROM, nonvolatile (NV), or battery-backed, RAM, and Flash EPROM. The
program memory may be in the microcontroller chip, or a separate component.

To save a program in EPROM, you must set the EPROM’s data and address pins to the
appropriate logic levels for each address and apply special programming voltages and
control signals to store the data at the selected address. The programming process is
sometimes called burning the EPROM. You erase the contents by exposing 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’s cheaper than a
windowed IC, it’s a good choice when a program is finished and the device is ready for
quantity production.

Several techniques are available for programming EPROMs and other memory chips. With
a manual programmer, you flip switches to toggle each bit and program the EPROM byte
by byte. This is acceptable for short programs, but quickly becomes tedious with a program
of any length. Computer control simplifies the job greatly. With an EPROM programmer
that connects to a personal computer, you can write a program at your keyboard, save it to
disk if you wish, and store the program in EPROM in a few easy steps. Data sheets for
EPROMs rarely specify the number of erase and reprogramming cycles a device is
guaranteed for, but a typical EPROM should endure 100 erase/program cycles, and usually
many more.

EEPROMs are much like EPROMs except that they are electrically erasable—no ultraviolet
source is required. Limitations of EEPROMs include slow speed, high cost, and a limited
number of times that they can be reprogrammed (typically 10,000 to 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 a
single IC package. When power is removed from the circuit, the lithium cell takes over and
preserves the information in RAM, for 10 years or more. You can reprogram an NVRAM
n infinite number of times, with the only limitation being battery life.

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

The 8052-BASIC uses two types of program memory. An 8-kilobyte, or 8K, on-chip ROM
stores the BASIC-52 interpreter. For storing the BASIC-52 programs that you write, the
BASIC-52 language has programming commands that enable you to save programs 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. Unlike EPROM, ROM,
EEPROM, and NVRAM, the contents of the RAM disappear when you 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 at least 1024 bytes
of external RAM as well.

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

Writing the Control Program

When it’s time to write the program that controls your project, the options include using
machine code, assembly language, or a higher-level language. Which programming language
you use depends on things like desired execution speed, program length, and
convenience, as well as what’s available in your price range.

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

Assembly language. One step removed from machine code is assembly language, where
abbreviations called mnemonics (memory aids) substitute for the machine codes. The
mnemonics are easier to remember than the machine codes they stand for. For example, in
the 8052’s assembly language, the mnemonic CLR C means clear the carry bit, and is easier
to remember than its binary code (11000011).

Since machine code is ultimately the only language that a CPU understands, you need some
way of translating assembly-language programs into machine code. For very short programs,
you can hand assemble, or translate the mnemonics yourself by looking up the machine
codes for each abbreviation. Another option is to use an assembler, which is software that
runs on a desktop computer and translates the mnemonics into machine code. Most
assemblers provide other features, such as formatting the program code and creating a listing
that shows both the machine-code and assembly-language versions of a program side
-by-side.

Higher-level languages. A disadvantage to assembly language is that each device family
has its own set of mnemonics, so you have to learn a new vocabulary for each family you
work with. To get around this problem, higher-level languages like C, Pascal, Fortran, Forth,
and BASIC follow a standard syntax so that programs are 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. In reality, each language tends to develop many
different dialects, depending on the chip and the preferences of the language’s vendor, so
porting a program to a different device isn’t always effortless. But there are many similarities
among the dialects of a single language, so, as with spoken language, a new dialect is easier
to learn than a whole new language.

Higher-level languages also simplify programming by allowing you to do in one or a few
lines what would require many lines of assembly code to accomplish.

Interpreters and compilers are two forms of higher-level languages. An interpreter translates
a program into machine code each time the program runs, while a compiler translates
only once, creating a new, executable file that the computer runs directly, without re-translating.
As a rule, interpreters are very convenient for shorter programs where execution speed isn’t
critical. With an interpreted language, you can run your program code immediately after you
write it, without a separate compile or assembly step. A compiler is a good choice when a
program is long or has to execute quickly. A single language like BASIC may be available
in both interpreted and compiled versions.

Each device family requires its own interpreter or compiler to translate the higher-level code
into the machine code for that device. In other words, you can’t use QuickBASIC for IBM
PCs to program an 8052 microcontroller—you need a compiler that generates program code
for the 8052.

Compared to an equivalent program written in assembly language, a compiled program
usually is larger and slower, so assembly language is the way to go if a program must be as
fast or as small as possible. A higher-level language also may not offer all of the abilities of
assembly code, though you can get around this by calling subroutines in assembly language
when necessary.

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

Testing and Debugging

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

Testing in EPROM. One way is to burn your program into EPROM, install the EPROM
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 try again, repeating as
many times as necessary until the system is operating properly.

Development systems. Another option is to use a development system. A typical development
system consists of a monitor program, which is a program stored in EPROM or other
memory in the microcontroller system, and a serial link to a personal computer. Using the
abilities of the monitor program, you can load your program from a personal computer into
RAM (instead of the more permanent EPROM) on the microcontroller system, then run the
program, modify it, and retry as often as necessary until the program is working properly.
Most development systems also allow single-stepping, setting breakpoints, and viewing and
changing the data in memory. In single-stepping, you run the program one step at time,
pausing after each step, so you can more easily monitor what the circuits and program are
doing at each step. A breakpoint is a program location where the program stops executing
and waits for a command to continue. You can set breakpoints at critical spots in your
program. At any breakpoint, you can view or change the contents of memory or perform
other tests.

Simulators. Another development tool is a simulator, which is software that runs on a
desktop computer and uses the video display to demonstrate what would happen if a specific
microprocessor or microcontroller were to run a particular program. You can look “inside”
the simulated chip, observe the contents of internal memory, and single-step or set breakpoints
to stop program execution at a desired program location or condition. In this way,
you can get a program working properly before you commit it to EPROM. One drawback
to simulators is that they can’t mimic all features of the chip of interest, especially
interrupt-response and timing characteristics.

Emulators. An in-circuit emulator (ICE) is hardware that replaces the microprocessor in
question by plugging into the microprocessor’s socket on the device you want to test. Like
a simulator, an emulator lets you control program execution and monitor what happens at
each program step. Microprocessor emulators typically are expensive. A ROM emulator is
a lower-cost option that simulates an EPROM (using RAM, for example) for program
storage, and usually provides the abilities of a development system as well.

The 8052-BASIC’s development system. The 8052-BASIC system and a personal computer
form a complete development system for writing, testing, and storing programs. The
personal computer’s keyboard and screen make it easy to write and run programs and view
the results.

BASIC-52 has many built-in debugging features that make it easy to test programs. You can
run a program immediately after writing it, without having to assemble, compile, or program
an EPROM. You can use a STOP statement and CONT (continue) command to set
breakpoints and resume executing your program. You can use PRINT statements to display
variables as the program runs. And, if you wish, you can use your personal computer for
writing programs off-line and uploading and downloading them to the 8052-BASIC system.

Feb 1, 2009

25 pin Parallel Port Pinout Details

Pin No.

Function

Pin No.

Function

1

Strobe

14

Auto Feed

2

Data 0

15

Error

3

Data 1

16

Init

4

Data 2

17

Select In

5

Data 3

18

Ground

6

Data 4

19

Ground

7

Data 5

20

Ground

8

Data 6

21

Ground

9

Data 7

22

Ground

10

Acknowledge

23

Ground

11

Busy

24

Ground

12

Paper Empty

25

Ground

13

Select

 

Connector may be reversed depending on which side is viewed. All pins are numbered.

image