Embedded System: An Embedded system can be defined as a computing device that can do a specific focused job.

Applications such as the air-conditioner, VCD player, DVD player, printer, fax machine, mobile phone etc. are examples of embedded systems. Each of these applications will have a processing unit and special hardware to meet the specific requirements of the application along with the embedded software that is executed by the processor for meeting that specific requirement of the job. The embedded software is also called as "firmware". In contrast the desktop/ laptop computer is general purpose computer. We can use it for a variety of applications such as playing games, word processing, accounting, software development and so on. Where as the software in the embedded systems are always fixed. Characteristics of Embedded Systems:  Embedded systems do a very specific task; they can't be programmed to do different things.  Embedded systems have limited resources, particularly the memory. Generally, they do not have secondary storage device such as the CDROM or the floppy disk.  Embedded systems have to work against some deadlines. A specific job has to complete with in the specific time.  Embedded systems are constrained for power. As many embedded systems operate through a battery, the power consumption has to be very low.  Embedded systems need to be highly reliable. Once in while, pressing ALT+CRTL+DEL is ok in your desktops, but you can't afford to reset your embedded system.  Some embedded systems have to operate in the extreme environmental conditions such as very high temperatures and humidity.  What is a Microcontroller? A microcontroller (often abbreviated MCU) is a single computer chip (integrated circuit) that executes a user program, normally for the purpose of controlling some device. Hence the name “Microcontroller”. The program is normally contained either in a second chip, called an EPROM, or within the same chip as the microcontroller itself. A microcontroller is normally found in devices such as microwave ovens, automobiles, keyboards, CD players, cell phones, VCRs, security systems, time & attendance clocks, etc. Microcontrollers are used in devices that require some amount of computing power but don’t require as much computing power as that provided by a complex (and expensive) 486 or Pentium system which generally requires a large amount of supporting

circuitry (large motherboards, hundreds of megabytes of RAM, hard drives, hard drive controllers, video cards, etc). A microwave oven just does not need that much computing power. Microcontroller-based systems are generally smaller, more reliable, and cheaper. They are ideal for the types of applications described above where cost and unit size are very important considerations. In such applications it is almost always desirable to produce circuits that require the smallest number of integrated circuits, that require the smallest amount of physical space, require the least amount of energy, and cost as little as possible. Note: A Microcontroller is a small CPU with many support devices built into the single chip. Self Contained (CPU, RAM, ROM, I/O pins, timers, interrupt sources, serial port, A/D and D/A interfaces etc). A microcontroller is designed such that for an application or Task Specific (Not a general-purpose computer). Microprocessor verses. Microcontroller Microprocessor:  CPU is stand-alone, RAM, ROM, I/O, timer are separate.  Designer can decide on the amount of ROM, RAM and I/O ports.  Expansive.  Versatility.  General-purpose. Microcontroller  CPU, RAM, ROM, I/O and timer are all on a single chip  Fix amount of on-chip ROM, RAM, I/O ports  For applications in which cost, power and space are critical  Single-purpose Criteria in Choosing a Microcontroller: 1. Meeting the computing needs of the task efficiently and cost effectively • speed, the amount of ROM and RAM, the number of I/O ports and timers, size, packaging, power consumption • easy to upgrade • cost per unit 2. Availability of software development tools • assemblers, debuggers, C compilers, emulator, simulator, technical support 3. Wide availability and reliable sources of the microcontrollers.

Facts responsible for success of microcontrollers: Their powerful, cleverly chosen electronics is able to control a variety of processes and devices (industrial automatics, voltage, temperature, engines, etc) independently or by means of I/O instruments such as switches, buttons, sensors, LCD screens, relays...etc

Their low cost makes them suitable for installing in places which attracted no such interest in the past. This is the fact accountable for today's market being swamped with cheap automatons and "intelligent" toys.

Writing and loading a program into microcontroller requires practically no previous schooling. All that is required is: any PC (software is very friendly and intuitive) and one simple device (programmer) for loading a written program into microcontroller.

So if you are into electronics, you will undoubtedly want to master the great potential of microcontrollers and put it to good use.

How does microcontroller work?
Although there are plenty of different microcontrollers and programs available, they all share a lot in common between them. This means that if you master one model, you will be able to handle them all eventually. Typical scenario goes something like this: 1. Power is off and all is still... Program is loaded, everything is set, with no indications of what is about to take place... 2. As soon as the power is on, it all happens too quickly to follow! First one to register the change is the control logic. It halts all the circuits except the quartz oscillator. First few milliseconds pass in hurried preparations and loading of parasitic capacitances... 3. As voltage reaches its maximum, oscillator frequency stabilizes. SFR registers are loaded with bits indicating the states of the subsystems, and all the pins are designated as input. Impulse sequence starts dictating the pace and the electronics

time is measured in microseconds and nanoseconds. .is now fully operational. From this point on.

number of available free pins is reduced as external ROM uses MCU's I/O ports.. Random Access Memory (RAM) RAM is used for temporary storage of data during runtime. which is an equivalent to the number of possible program instructions. RAM memory does not retain its stored information when the power is interrupted. For example: by writing zeros and ones to the SFR register which controls an I/O port. Apparently. Program counter is reset to zero address of the program memory. Both options have their pros and cons. EEPROM Memory EEPROM is a special kind of memory not available with all MCUs. Internal ROM is usually smaller and more costly but it provides more possibilities for connecting to the outside world. but is also saved after the power is off (as with ROM). But it would not be especially useful if it was not for additional systems which round out the MCU: Read Only Memory (ROM) ROM is the memory which stores the program to be executed. At the same time. and is also pretty simple. Instruction is sent from this address to the instruction decoder where it is interpreted and executed promptly. its size dictates the maximal program length. ROM spans from 512 bytes to 64kB. SFR Registers Special Function Registers are special elements of RAM. 5.4. (several millions of times per second) Obviously. their purpose predefined by the manufacturer. it all works at tremendous speeds. Each of these registers is named and controls a certain subsystem of MCU. Its contents can be changed during runtime (as with RAM). external memory chip makes the microcontroller cheaper and allows for longer programs. Program counter is incremented by one as the whole process plays out again. . It can be internal or external with respect to the microcontroller. RAM spans from tens of bytes to several kilobytes..

shifting. value of a counter can be changed anytime with a "jump" to a new program memory location as a result.. It can be described as a working desk for performing operations on data (adding. Program Counter increase carries on steadily. Control Logic As the name implies. and represents a basic memory cell. Status Register is specifically associated with the accumulator. the value of counter increments by 1.. It comprises several parts. Program Counter This is the "engine" which starts the program and points to the memory address of the instruction to be executed. and it cannot be manipulated. this is the register which holds the result of the operation. +1. Arithmetical Logical Unit (ALU) – is in charge of all mathematical and logical operations over data. Capabilities of this circuit are represented through the so called "instruction set" which is different for every MCU. Due to this automatic increase. +1. It monitors the status of the accumulator's content at all times (is zero. Also.each of these pins can be designated as input or output (each register bit corresponds to one of the port pins). program executes one instruction at a time. Immediately upon its execution.. +1. etc).   Accumulator – a special SFR register highly interconnected with ALU. just the way it was written. etc). However. Of SFR registers. Register Register is a byte physically realized as electronic component. the most important ones including:  Instructions Decoder – part of the electronics which "recognizes" different program instructions and directs the other circuits accordingly. Upon performing a jump to the specified destination. there is also an address part not readily accessible. . Beside the 8 bits available to the user. This is how routines and branch instructions are carried out.. is greater than zero. this is the "Big Brother" which supervises and controls every aspect of operations within MCU.

if your system uses 20MHz quartz-crystal. When writing a code for MCU in one of the higher programming languages. each register can be given an arbitrary name. In both cases. Oscillator This is the rhythm section of the miniature orchestra. This happens because instructions take several steps to be accomplished (execution period of different instructions may vary on different MCUs). Stable pace provided by this instrument allows harmonious and synchronous functioning of all other parts of MCU. filling the register resets the counter and the occurrence is recorded in a particular bit of SFR register (Overflow flag). Why I/O? Because every pin can be designated as eiher input or output to suit user's needs. I/O Ports To be of any practical use. execution period of one program instruction will not be 50 ns. timers are 8 or 16-bit registers whose value automatically increases upon an impulse. every MCU has one or more registers (also known as ports) which are connected to the pins on its case. which proved to be useful. SFR registers are named (differently with different MCUs) and each has its role. Commonly.  ROM and RAM registers are nameless and are usually peers. For this purpose. This makes possible to measure longer . Timers Majority of programs utilizes these miniature electronic "stopwatches". If timer is stimulated by an internal MCU oscillator. It can also work without an element for stabilizing frequency (as RC oscillator). If timer is triggered by impulses from an external source. microcontroller needs to be connected to other electronics and to the environs. elapsed time = T2-T1). 400 or” whole” 800 ns. Therefore. Commonly. it can be used for measuring time between two occurrences (register value at the start of measuring = T1. oscillator frequency is stabilized using a quartz-crystal or a ceramic resonator. register value at the end of measuring = T2. instrument behaves like a counter. Note that instructions are executed at a rate several times slower than the pace dictated by the oscillator. but more likely 200.

MCU is reset. It is a timer with input connected to an independent MCU RC oscillator.time periods. If Watchdog is enabled. executes within a number of simpler or more complex loops. Also. key places in the program were added an instruction for resetting the Watchdog. If. If. The idea is to prevent that from happening by means of special instruction. for some reason. electrical interference is common) Program Counter "gets stuck" at a memory location with no return. . MCU is reset every time it overflows. beside the regular instructions. i. this flag can cause an interrupt for breaking the program and carrying out a designated routine (see the image). the ever-increasing Watchdog Timer eventually overflows and voila . its safeguard function would pass unnoticed.e. Whole concept is based upon a fact that every program technically "goes around". (in industrial environment. Watchdog Timer The name itself implies the role of this instrument. if enabled. and the program execution starts anew (much as if the power had just been turned on).

If not preinstalled. or 12-bit and this is sufficient for most tasks. 10. Two 16-bit timers / counters. i.  Reset pin – frequently marked as MCLR (Master Clear Reset) is used for "external" reset of microcontroller by bringing the logical zero or one (depending on the MCU). converters are 8. routines can be executed within other routines.e. brown out promptly resets the entire electronics. this can cause their uncontrolled behavior. brown out reset circuit is included within MCU. Usually there are several separate channels so that multiple analog values can be measured simultaneously. It can be multileveled. Power Supply Circuit Two features of the MCU power supply circuit deserve your attention:  Brown out – this is a potentially dangerous state which occurs during the shutdown or in situations when voltage "oscillates" on the edge of the allowed range due to strong interference. Stack Stack is a special part of RAM for storing the current value of Program Counter. 32 I/O lines.A/D Converter Another convenient instrument not available with all MCUs. If voltage drops below the specified value for high-voltage elements of MCU. What is 8051 and 8052? Features of Intel 8051:     4KB of Flash memory for storing the program. . a simple external brown out reset circuit can be connected to this pin. Since microcontroller comprises a number of elements with various voltage ranges. To prevent this from happening. 128 bytes of internal RAM for storing variables. Commonly. so that program could "know" where to pick up after the interrupt routine.

Major companies producing 8051 and 8052 controller derivatives: Intel. Siemens.  6 interrupt sources. Philips. The term derivative chip. Derivative Chips Intel wisely licensed their MCU core to other semiconductor firms. 32 I/O lines. 256 bytes of internal RAM for storing variables. This allowed the architecture to become an industry-wide standard. Atmel. Programmable UART serial communication. etc . National Semiconductors. Programmable UART serial communication. Dallas. A derivative chip will generally (but not always) be able to execute a standard 8051 or 8052 program without modification. There are currently hundreds of derivative chips produced by dozens of semiconductor firms. Features of Intel 8052:       8KB of Flash memory for storing the program. more than 20 years later. Three 16-bit timers / counters. will refer to any 8051 or 8052compatible MCU that is produced by any semiconductor firm. 8 interrupt sources. Now. dozens of semiconductor companies produce microcontrollers that are based on the original 8051 and 8052 core.

Depending on the device's purpose and environs. Each of these pins can be used as either input or output according to your needs. positive voltage impulse on this pin resets the MCU. In another words. reset-upon-start circuit or a brown out reset circuit (covered in the previous chapter).0 and P1. .  9: Reset Signal. Also. Bringing this pin back to logical state zero starts the program anew as if the power had just been turned on. It is utilized in situations when power fails to reach its optimal voltage. The image shows one simple circuit for safe reset upon starting the controller.Block diagram and Pin configuration of 8051:  1–8: Port 1. pins 1 and 2 (P1. high logical state on this input halts the MCU and clears all the registers.1) have special functions associated with Timer 2. this pin is usually connected to the push-button.

 10-17: Port 3. Input and output of internal oscillator. However. Pin 11: TXD .clock input of counter 0 Pin 15: T1 . Capacitances within the oscillator mechanism (see the image) are not critical and are normally about 30pF.input for interrupt 1 Pin 14: T0 . Quartz crystal controlling the frequency commonly connects to these pins.serial output for asynchronous communication or clock output for synchronous communication Pin 12: INT0 . In that case. Instead of a quartz crystal.serial input for asynchronous communication or serial output for synchronous communication.clock input of counter 1 Pin 16: WR . . miniature ceramic resonators can be used for dictating the pace. As with Port 1.input for interrupt 0 Pin 13: INT1 . each of these pins can be used as universal input or output. each pin of Port 3 has an alternative function:  Pin 10: RXD .signal for reading from external RAM memory         18-19: X2 and X1. manufacturers recommend using somewhat higher capacitances (about 47 pF).signal for writing to external (add-on) RAM memory Pin 17: RD . New MCUs work at frequencies from 0Hz to 50MHz+.

Before each reading of the external memory. data from port can be multiplexed and the port simultaneously used for transferring both addresses and data. Ground 21. and uses it as part of the address for memory chip. It is important to note that in cases when not all the 8 bits are used for addressing the memory (i. and then the external (if present). If external memory is present. memorizes the state of port P0 upon receiving a signal from ALE pin. and port P0 is used as Data Bus.28: Port 2. the rest of the unused bits are not available as input/output. first the internal. Bringing this pin to the logical state zero (mass) designates the ports P2 and P3 for transferring addresses regardless of the presence of the internal memory.  31: EA. addresses A8 – A15. This means that even if there is a program loaded in the MCU it will not be executed. In this way.e. Conversely. this is the location of the higher address byte. signal on ALE is off.  30: ALE. pins of Port 2 act as universal input/output. During the second part of the mechanical MCU cycle. MCU sends the lower byte of the address register (addresses A0 – A7) to port P0 and activates the output ALE. by adding only one cheap integrated circuit. bringing the pin to the high logical state causes the controller to use both memories. but the one from the external ROM will be used instead. . If external ROM is used for storing the program.  29: PSEN. If external memory is not present. External register (74HCT373 or 74HCT375 circuits are common). memory is smaller than 64kB). MCU activates this bit (brings to low state) upon each reading of byte (instruction) from program memory. PSEN is directly connected to its control pins.  20: GND. i.e.

P0 behaves as address output (A0 – A7) when ALE pin is at high logical level. external "pull up" resistor needs to be added for connecting the pin to the positive pole. Clearing a port bit grounds the appropriate pin on the case (0V). external "pull up" resistor needs to be added for connecting the pin to the positive pole. if particular pin on the case is needed as input. If external memory is used. the appropriate bit of I/O port should be set. the port itself is in charge: 0=output. the appropriate bit of I/O port should be cleared. Unlike the case with other controllers. Similar to Port 2. pins of Port 0 can be used as universal input/output. When designated as output.  Therefore. Unlike other ports. This provides the user with 32 I/O lines for connecting MCU to the environs. generating +5V as a side effect (as with every TTL input). there is no specific SFR register for designating pins as input or output.  40: VCC. 1=input. Power +5V Input – Output (I/O) Ports Every MCU from 8051 family has 4 I/O ports of 8 bits each. Another feature of this port comes to play when it has been designated as output. Therefore. This will designate the pin as input. Setting a port bit makes the pin act as high impedance. 32-39: Port 0. Similarly. to get one (5V) on the output. . otherwise all bits of the port are either input or output. pin acts as "open drain". if external memory is not used. This will generate 0V on the specified controller pin. or as data output (Data Bus) when ALE pin is at low logical level. it contains the lower address byte (addresses A0-A7). to get positive logic (5V) at output. pin of Port 0 acts as high impedance offering the infinite input resistance with no "inner" voltage. Instead. Port 0 lacks the "pull up" resistor (resistor with +5V on one end). Port 0 Port 0 has two fold role: if external memory is used. If particular pin on the case is needed as output. This seemingly insignificant change has the following consequences:  When designated as input.

the pin in question has to be designated as input. Note: As can be seen from the individual descriptions of the ports. Depending on the particular model from 8051 family. it can be used as universal I/O port. the appropriate bit of register P3 needs to be set. For example: if utilizing port as output with high level (5V). Memory During the runtime. Port 3 is similar to Port 0.e.Port 1 This is "true" I/O port. but it could be added externally in a form of a separate chip. Port 1 is fully compatible with TTL circuits. 8051 can address up to 64KB of external memory. similar to Port 0. These MCUs can be recognized by their . each pin of Port 3 has an alternate function. they all share highly similar structure. microcontroller uses two different types of memory: one for holding the program being executed (ROM memory). These can be separate memory blocks. and the other for temporary storage of data and auxiliary variables (RAM memory). Port 2 When using external memory. i. devoid of dual function characteristic for Port 0. (separate RAM chip and ROM chip) totaling 128KB of memory on MCU which is a real programming goody. In order to use one of these functions. ROM memory First models from 8051 family lacked the internal program memory. this is usually few kilobytes of ROM and 128/256 bytes of RAM. Having the "pull up" resistor. Otherwise. you need to consider which task should be assigned to which port. Port 3 Beside its role as universal I/O port. However. avoid using Port 0 as its pins cannot produce high logical level without an additional resistor connected to +5V(pull up resistors). From a hardware standpoint. this port contains the higher address byte (addresses A8– A15). This amount is built-in and is sufficient for common tasks performed "independently" by the MCU. However.

RAM spanned 256 locations. first 128 registers. New models have built-in ROM. i. Many manufacturers deliver controllers that can be programmed directly by the user. With some models internal memory cannot be programmed directly by the user. I/O ports. Apart from that. while new models feature additional 128 registers. the user needs to proceed the program to the manufacturer.mark which begins with 803 (e. RAM memory As previously stated. With older versions.g. and this part of RAM is split into several blocks as can be seen in the image below. etc. although there are substantial variations.e. buffer for serial connection. These come in a ceramic case with an opening (EPROM version) or in a plastic case without an opening (EEPROM version). This book deals with one of the latter models that can be programmed via simple programmer. 8031 or 8032). there are MCU models ideal for experimentation and small specialized series. Locations that are available to the user span addresses from 0 to 7Fh. Obviously. First 256 memory locations form the basis of RAM (addresses 0 – FFh) of every 8051 MCU. Fortunately. Instead. RAM comprises a number of registers: hardware counters and timers. even if the chip has already been mounted to the designated device. . RAM is also called as Data memory used for storing temporary data and auxiliary results generated during the runtime. so that the MCU can be programmed (masked) appropriately in the process of fabrication. this option is cost-effective only for large series.

  Third is the group of available registers at addresses 2Fh – 7Fh (total of 80 locations) without special features or a preset purpose. meaning that every belonging bit has its own address (0 to 7Fh). But it is not all that simple. Since the block comprises 16 of these registers. The problem . marked as R0 . Second memory block (range 20h – 2Fh) is bit-addressable.. while bit 7 of byte 2Fh has bit address 7Fh). To address these. there is a total of 128 addressable bits. latest 8051 models were added an extra memory block of 128 locations. (Bit 0 of byte 20h has bit address 0. the parent bank has to be selected. Extra Memory Block To satisfy the programmers' ever-increasing demands for RAM. First block comprises 4 "banks" of 8 registers each.R7..

reaching only the first 256 locations. a little trick had to be applied in order to keep the existing 8-bit architecture for the sake of compatibility with older models. The first one is active when reading byte from the external data memory (RAM). From user's point of view it's all very simple. there is always an option of adding two external 64KB memory chips. The idea is to make the additional memory block share the addresses with the existent locations intended for SFR registers (80h . indirect addressing is used. Both signals are active on low logical level. direct addressing is used. .7) and PSEN#. For distinguishing these two physically separate memory areas. When added. 8051 MCU has two separate read signals.FFh). known as Harvard architecture. Memory Expanding In case the built-in amount of memory (either RAM or ROM) is not sufficient for your needs. different methods of addressing are used: if SFR registers are in question. for extra RAM locations. RD# (P3. they are addressed and accessed via I/O ports P2 and P3.lies in the fact that the electronics which addresses RAM employs 1 byte (8 bits). Therefore. The following image shows a typical scheme for such expansion using separate chips for RAM and ROM. and the second one is active when reading byte from the external program memory (ROM). because if properly connected most of the job is carried out automatically by MCU.

functioning as both data memory and program memory simultaneously (only one memory chip is used). This approach is known as Von Neumann architecture. Since the memory is off-chip the assembly language instructions to access it are . Using the Harvard architecture effectively doubles MCU memory. output of AND circuit is low if any of the two inputs is low.Memory can be also mapped as a single block. these two signals were combined via logical AND. but that's not the only advantage offered by the method. To be able to read the same block using RD# or PSEN#. Although 8051 and 8052s contain a small amount of on-chip RAM and ROMs. External RAM is any random access memory that is found off-chip. External RAM and ROMs are also supported. In this way. As the name suggests. Keeping the program code separated from the data makes the controller more reliable since there is no writing to the program memory.

interrupt. For example. To increment a 1-byte value stored in External RAM requires 4 instructions and 7 instruction cycles. the basic core shared by 8051 MCUs has but 22 registers. programs are limited to 64K. etc).slower and less flexible. The rest has been left open intentionally to allow future upgrades while retaining the compatibility with earlier models. Hardware Tip: Some manufacturers such as Dallas. However. 8051 programs are limited to 64K. Some compilers offer ways to get around this limit when used with specially wired hardware and a technique known as memory banking. Every register and each of the belonging bits has its name. to increment an Internal RAM location by 1 requires only 1 instruction and 1 instruction cycle. without such special compilers and hardware. the 8052 supports External RAM and External ROM up to 64K bytes. . Programming Tip: Since memory is restricted to 64K. specified address in RAM and strictly defined role (e. external memory is 7 times slower and requires 4 times as much program memory! What External RAM loses in speed and flexibility it gains in quantity. While Internal RAM is normally limited to 256 bytes in 8052 and 128 bytes with 8051s. In this case. serial connection. Intel and Philips have special 8051 derivatives that can address several megabytes of memory SFR Registers (Special Function Registers) SFR registers can be seen as a sort of control panel for managing and monitoring the microcontroller. controlling the timer. This fact makes possible to use programs developed for obsolete models long ago.g. Although there are 128 available memory slots for allocating SFR registers.

it has to go through the accumulator.Accumulator Accumulator is a general purpose register which stores runtime results. Before performing any operation upon an operand. operand has to be stored in the accumulator. Due to its versatile role. . When transferring data from one register to another. Results of arithmetical operations (performed by ALU) are also stored in the accumulator. this is the most frequently used register. essential part of every MCU.

one for input. Every port bit corresponds to one of the pins on the casing. serve for temporary storage of variables and runtime results. Vice versa. . Thus. all port bits are set. you may store the other number in "B" and make use of these two instructions. When compiled (translated into hex code comprehensible to the controller).I/O Ports If external memory and system for serial communication are not used. P1. Note: Since registers are called upon by the name during the writing of program. user has 4 ports (32 I/O lines) at disposal for communicating to the environs. The "B" register is only used implicitly by two 8052 instructions: MUL AB and DIV AB. program will automatically replace register names with the appropriate addresses. "R" registers deserve to be mentioned at this point. state of port bit designates the pin as input or output: zero for output. designating all corresponding pins as input. voltage on input pins is interpreted into bit logic on port. At the same time. Other instructions can use this register as a secondary accumulator (A). while reading. After reset. B register The "B" register is very similar to the Accumulator in the sense that it may hold an 8-bit (1-byte) value. and like the accumulator.R7) Although not true SFR registers. if you want to quickly and easily multiply or divide A by another number. They are located within one of the 4 banks in RAM. Two bits of PSW register are in command which bank will hold "R" registers. programmer needs not to know their exact addresses. P3 . P0. P2. thus controlling the voltage on output (0 or 5V)."R" registers (R0 .

bit is automatically set (1).  . OV is set (1). according to the following table. With the beginning of every new routine. RS1 0 0 1 1 RS0 0 1 0 1 Location in RAM Bank 0 Bank 1 Bank 2 Bank 3 00h-07h 08h-0Fh 10h-17h 18h-1Fh    .Overflow bit. Stack Pointer increases by 1. and is used for managing program during the runtime.  P (bit 0) . RS1. It is commonly used in data transfers via serial connection. SP decreases by 1.Stack Pointer (SP) The number in Stack Pointer points to the location of the last "valid" address within the Stack. If another value is written to SP. RS0 (bits 3 and 4) . If result of arithmetical operation exceeds 255 (decimal). ALU automatically makes changes to certain bits of this register. upon return from routine. meaning that the amount of RAM allocated to Stack begins from this memory location.(bit 1) . OV (bit 2) . otherwise it's cleared (0). this register contains number 7. After reset (or turning the power on). entire Stack moves to the new specified location.This bit is intended for the upcoming MCU models and shouldn't be used. Masking these bits stores registers R0 R7 into one of the 4 banks in RAM.Parity bit. otherwise it's cleared (0). If numeral in accumulator is even.Register select. Program Status Word (PSW) Program Status Word is one of the most important SFR registers.

It is used by the 8052 to store values that the user program manually pushes onto the stack as well as to store the return addresses for CALLs and interrupt service routines (more on these topics later).Auxiliary Carry Flag. it is commonly used for temporary storage of data and runtime results not related to memory locations. it will be taken from the Internal RAM address pointed to by SP and SP will subsequently be decremented by 1. Auxiliary (ninth) bit for arithmetical and shift operations. The stack is defined and controlled by a Special Function Register called the Stack Pointer. If a value is removed from the stack. SP is initialized to 07h when an 8052 is first booted. Data Pointer's 16 bits are used for addressing external memory. If a value is pushed onto the stack. CY (bit 7) . Since this is the only 16-bit register available to programmer. SP will first be incremented and then the value will be inserted in Internal RAM at the address now pointed to by SP.  Data Pointer Data Pointer actually consists of two registers: DPH (Data Pointer High) and DPL (Data Pointer Low). The Stack The stack is a last in.Flag 0.  F0 (bit 5) . first out (LIFO). AC (bit 6) .Carry Flag. This means the . Storage area that exists in Internal RAM. SP. used only for operations with BCD (Binary Coded Decimals). holds a value between 0 and 255 that represents the Internal RAM address of the end of the current stack. as a standard 8-bit SFR. or SP. An all-purpose flag.

e. i.3. if you will be using bit variables it is usually a good idea to initialize the stack pointer to some value greater than 2Fh to guarantee that your bit variables are protected from the stack. to add the value of R4 to the Accumulator. However. R3. This can be seen in the bright green section of the memory map. Specifically. otherwise the stack will overwrite your alternate register banks. R6. We will talk about the register banks and Bit Memory below.. R4 is synonymous with 14h. or 3. R4 will no longer be the same as Internal RAM address 04h. etc. This means that the stack will start at address 08h and expand upwards. If you will be using the alternate register banks (banks 1. When the 8052 is first booted up register bank 0 (addresses 00h through 07h) is used by default. Since R4 is really Internal RAM address 04h. the above instruction effectively accomplishes the same thing as the previous ADD instruction. These "R" registers are numbered from 0 through 7 (R0. But watch out! As the memory map shows. register banks 1. R5. your program may instruct the 8052 to use one of the alternate register banks.first value to be pushed onto the stack will be placed at Internal RAM address 08h (07h + 1). R1. Similarly. 2. Programming Tip: By default. and R7) and are generally used to assist in manipulating values and moving data from one memory location to another. the 8052 has four distinct register banks. the second will be placed at 09h. the 8052 initializes the Stack Pointer (SP) to 07h when the microcontroller is booted. Thus the above instruction accomplishes the same thing as the following operation: ADD A. register R4 will now be synonymous with Internal RAM address 0Ch. leaving the result in the Accumulator.3 Register Banks The 8052 uses 8 "R" registers which are used in many of its instructions. R2. 2. However. If you select register bank 2. Setting or clearing the bits RS0 and RS1 in the Program Status Word (PSW) Special Function Register selects the register bank. R4. For example: . the "R" Register R4 is really part of Internal RAM. R4 is address 04h of Internal RAM. For example. 2 or 3) you must initialize the stack pointer to an address above the highest register bank you will be using. if your program instructs the 8052 to use register bank 1.04H This instruction adds the value found in Internal RAM address 04h to the value of the Accumulator. In this case. For example. and if you select register bank 3 it is synonymous with address 1Ch.1. as the memory map shows.R4 Thus if the Accumulator (A) contained the value 6 and R4 contained the value 3. the Accumulator would contain the value 9 after this instruction was executed. we would execute the following assembly language instruction: ADD A.

bank 0). gives the developer the ability to access a number of bit variables directly with simple instructions to set. Thus.#10H PSW. or 3. For example. Programming Tip: If you only use the first register bank (i. numbered 00h through 7Fh. always remember that the register banks really reside in the first 32 bytes of Internal RAM.MOV MOV MOV MOV PSW. sets . 2.e. you may use Internal RAM locations 08h through 1Fh for your own use. If you plan to use register banks 1. sets .#0FFH is equivalent to the instructions: SETB SETB SETB SETB SETB SETB SETB SETB 00H 01H 02H 03H 04H 05H 06H 07H . is really a part of Internal RAM. Bit Memory The 8052. like the Register Banks above. However. clear. being a communications and control-oriented microcontroller that often has to deal with “ON” and “off” situations.#08H PSW. if you write the value FFh to Internal RAM address 20h you’ve effectively set bits 00h through 07h. sets . and compare these bits. There are 128 bit variables available to the developer. The developer may make use of these variables with commands such as SETB and CLR. These variables may be either 1 or 0. be very careful about using addresses below 20h as you may end up overwriting the value of "R" registers from other register banks.#00H PSW. That is to say that the instruction: MOV 20H. Infact. sets register bank 0 register bank 1 register bank 2 register bank 3 The above instructions will make more sense after we cover the topics of Special Function Registers.#18H . the 128 bit variables occupy the 16 bytes of Internal RAM from 20h through 2Fh. especially when dealing with interrupts (we'll talk about interrupts later). to set bit number 24h(hex) to 1 you would execute the instruction: SETB 24H It is important to note that Bit Memory. The concept of register banks adds a great level of flexibility to the 8052.

1 output line you may either execute: MOV P0.3.7 are all clear (0) and you want to turn on the P0. It’s really just a subset of Internal RAM. Programming Tip: If your program does not use bit variables you may use Internal RAM locations 20h through 2Fh for your own use. Bits 88h through 8Fh refer to bits 0 through 7 of SFR 88h. This means that the stack will start at address 08h and expand upwards. four SFRs permit access to the 8052. in some cases.0 line without affecting the status of any of the other P0 output lines. if you will be using bit variables it is usually a good idea to initialize the stack pointer to some value greater than 2Fh to guarantee that your bit variables are protected from the stack.s serial port. Bits 90h through 97F refer to bits 0 through 7 of 90h.0 through P0.#02H or you may execute: SETB 81H Both of these instructions accomplish the same thing. For example. otherwise the stack will overwrite your alternate register banks. Bit Memory 80h and above are used to access certain SFRs (see below) on a bit-by-bit basis. This is a complicated way of saying that bits 80h through 87h refer to bits 0 through 7 of SFR 80h. may not be acceptable. 2. While Bit Memory 00h through 7Fh are for developer-defined functions in their programs. But always keep in mind that it is just a subset of Internal RAM--and that operations performed on Internal RAM can change the values of the bit variables. 2 or 3) you must initialize the stack pointer to an address above the highest register bank you will be using. Another SFR allows a program to read or write to the 8052. control and access timers. etc. Programming Tip: By default. the 8052 initialize the Stack Pointer (SP) to 07h when the microcontroller is booted. Since the 8052 provide special instructions to access these 16 bytes of memory on a bit-by-bit basis it is useful to think of it as a separate type of memory. and configure the 8052. if output lines P0. Bit Memory isn’t really a new type of memory.s 32 input/output lines (8 lines per SFR). Similarly. The MOV command effectively turns off all the other output lines which. However. When dealing with bit addresses of 80h and above remember that the bits refer to the bits of corresponding SFRs that are divisible by 8.As illustrated above. Other SFRs allow the user to set the serial baud rate. If you will be using the alternate register banks (banks 1. For example. using the SETB command will turn on the P0. When programming. SFRs have the .s interrupt system.2 Special Function Register (SFR) Memory Special Function Registers (SFRs) are areas of memory that control specific functionality of the 8052 MCU. If you plan to use bit variables be very careful about using addresses from 20h through 2Fh as you may end up overwriting the value of your bits.

Not all addresses above 80h are assigned to SFRs. Special Function Registers (SFRs) The 8052 is a flexible microcontroller with a relatively large number of modes of operation. All other addresses in the SFR range (80h through FFh) are considered invalid. The upper 128 bytes of Internal RAM must be accessed using. For example. Which will be explained in a subsequent chapter. Thus. direct address. more on that soon). if you want to write the value "1" to the 8052. The following chart provides a graphical presentation of the 8052's SFRs. Programming Tip #1: SFRs are used to control the way the 8052 functions. Programming Tip #2: Since direct access to addresses 80h through FFh refers to SFRs. and their address. this area may NOT be used as additional RAM memory even if a given address has not been assigned to an SFR. This is not the case.#01H As you can see. direct access cannot be used to access Internal RAM addresses 80h through FFh.s serial port you would write this value to the SBUF SFR. to write the value "1" to the serial port you would execute the instruction: MOV 99H. The only difference is that Internal RAM is addressed in direct mode. it appears as if the SFR is part of Internal Memory. any instruction that has an address of 00h through 7Fh refers to an Internal RAM memory address. . Each SFR has an address (80h through FFh) and a name. there are only 26 SFRs in a standard 8052 (21 with an 8051). with addresses 00h through 7Fh whereas SFR registers are accessed in the range of 80h through FFh.illusion of being Internal Memory. Your program may inspect and/or change the operating mode of the 8052 by manipulating the values of the Special Function Registers (SFRs). if you want to write the value "1" to Internal RAM location 50h you would execute the instruction: MOV 50H. However. Each SFR has a specific purpose and format that will be discussed later. any instruction with an address of 80h through FFh refers to an SFR control register. SFRs are accessed as if they were normal Internal RAM. their names. Writing to or reading from these registers may produce undefined values or behavior. which has an SFR address of 99 Hex.#01H Similarly. When using this method of memory access (it’s called. As you can see. although the address range of 80h through FFh offers 128 possible addresses. Indirect Addressing.

Actually. a constant value is specified in the instruction itself. put a leading 0. The constants can be decimal numbers. #D3H . Invalid MOV A. the ASCII code of the character is processed here. Example: MOV a. 8051 Addressing Modes Immediate Addressing: In this addressing mode. can be accessed by certain instructions that carry a 3-bit register specification within the opcode of the instruction. The “#” symbol precedes the constant values in the assembly instructions. since this mode eliminates an address byte. Decimal numbers do not require any suffix. binary numbers or characters.g. one of the eight registers in the selected bank is accessed. Example: MOV A. If not. containing registers R0 through R7. valid 2. Moreover. hexadecimal numbers. R5 . . loads the Accumulator With the decimal number 100 4. a hexadecimal number must start with a digit. When the instruction is executed. #”Z” Register Addressing: The register banks.g. 1. add the content of R5 to accumulator Direct Addressing: In direct addressing the operand is specified by an 8-bit address field in the instruction. #100 . Example: MOV A. Doing so may provoke undefined behavior and may cause your program to be incompatible with other 8052-derivatives that use the given SFR for some other purpose. #0D3H . 3AH). Hexadecimal numbers are written with “H” suffix (e. Instructions that access the registers this way are code efficient. Characters must be written between double quotation marks (e. Binary numbers are written with a “B” suffix (e.g. then you have to write it in a program as 0D3H.Programming Tip: It is recommended that you not read or write to SFR addresses that have not been assigned to an SFR. Example: ADD A. Example: MOV A. if the hexadecimal number that you want to specify is D3H. 01000101B). Only internal data memory (including SFRs) can be directly addressed. "Z"). For example. #01000101B 3.

Increment ACC . accessing external memory with the MOVX @DPTR instruction is indirect addressing since the address to be accessed is referred to indirectly by the DPTR register. loop . move ACC into mem location .move the content of internal data memory location whose address is in register R0. The address register for 16-bit addresses can only be the 16-bit “data pointer” register. Thus while this approach is technically "indirect. The address register for 8-bit addresses can only be R0 or R1 of the selected bank. The 16-bit register DPTR and register A are used to form the address of the data element stored in on-chip ROM.add the content of the B register to acc In the latter example the address of the B register (F0) register is actually used in the encoded form. Indirect Addressing: In indirect addressing the instruction specifies a register which contains the address of the operand. move the content of internal data memory Address 66H to acc . Example: MOV A. Q) Write an ALP to fill 10 successive locations Starting at 40h with decimal numbers 0 to 9.@R0 . DPTR (this is not the case in labs). Increment RO to point to next address Programming Tip: Technically." I called it "External Direct" since it is the most direct method of accessing a specific external RAM memory location and to differentiate it from the following addressing mode (External Indirect) which is very similar to the "indirect addressing" Indexed addressing mode: Indexed addressing mode is widely used in accessing data elements of lookup tables entries located in the program ROM space of the 8051. However. B . load counter . The “@” symbol is used before the register is to specify the indirect addressing mode in instructions.A INC A INC R0 DJNZ R2.#40H MOV R2. Initialize ACC to zero .#10 loop: MOV @R0.The instruction used for this is MOVC A. Because the data elements .@A+DPTR. Start: CLR A MOV R0. 30H ADD A. assign a pointer to mem location 40h . Both internal and external data memory can be indirectly addressed (SFRs are not indirectly addressed).Examples:MOV A. to directly access a specific external RAM memory location the most direct way is to load DPTR with the address in question and access it with the MOVX instruction.

After the program execution is completed we have the characters of the string starting from 40H.are stored in the program space Rom of the 8051. The instruction “MOVC A. For example. This is moved to 40H location. Instructions that refer to the Accumulator as A resembles an accumulator specific opcodes. which holds the ASCII value of “H” and it is moved into the location 41H. some instructions always operate on the Accumulator. it uses the instruction MOVC instead of MOV. The opcode itself does that. Register A contains the ASCII value for “T”. the DPTR is incremented to make DPTR = 201. The “C” means code. Complement accumulator .#MSG mov r0. Example: CPL A .#40h mov r2. Accumulator is set to 0 again to get contents of the next ROM location 201H.a inc DPTR inc r0 djnz r2. Next.loop nop org 0200h MSG: DB 'THUNDER' We start with DPTR = 200H. NOTE: Register-Specific Instructions. Some instructions are specific to a certain register.@A+dptr mov @r0.#7 loop: clr a movc a. org 0000h start: mov dptr. Write a program to access the string THUNDER which is stored at ROM locations starting from 200hand also store the result at RAM locations starting from 40h. In this instruction the contents of A are added to the 16 bit register DPTR to form 16-bit address of the needed data.@A+DPTR” moves the contents of ROM location 200H (200H + 0 = 200H ) to register A. so no address byte is needed to point to it. and A = 0.

Some notations: bitAddr: Bit address value (00-FF) data8: Immediate 8-bit data value data16: Immedate 16-bit data value address16: 16-bit code address direct: Direct address (IRAM 00-7F. Add Value with Carry Syntax: ADD A. The Carry bit (C) is set if there is a carry-out of bit 7. the . in the range of 0x00 through 0xFF. Add Value. The Program Counter is then updated so that program execution continues at the indicated address.operand ADD and ADDC both add the value operand to the value of the Accumulator. if the unsigned summed value of the low nibble of the Accumulator. Absolute Call within 2k Block Syntax: ACALL codeAddress ACALL unconditionally calls a subroutine at the indicated code address. Otherwise. Cycles: The number of machine cycles required to execute the instruction. Bits 3-7 of the most-significant-byte of the Program Counter remain unchaged. In other words. that represents the given instruction in machine code. ADD. the Carry bit is cleared. ADDC . The value operand is not affected. SFR 80-FF) relAddr: Relative address (-127 to +128 bytes) ACALL . The Auxillary Carry (AC) bit is set if there is a carry-out of bit 3. Since only 11 bits of the Program Counter are affected by ACALL. operand and (in the case of ADDC) the Carry flag exceeds 255 Carry is set. Otherwise. most-significant-byte second. The new value for the Program Counter is calculated by replacing the least-significantbyte of the Program Counter with the second byte of the ACALL instruction. OpCode: The operation code. least-significant-byte first.operand Syntax: ADDC A. operand and (in the case of ADDC) the Carry flag exceeds 15 the Auxillary Carry flag is set. and replacing bits 0-2 of the most-significantbyte of the Program Counter with bits 5-7 of the opcode value. In other words. Bytes: The total number of bytes (including the opcode byte) that make up the instruction. calls may only be made to routines located within the same 2k block as the first byte that follows ACALL. ADD and ADDC function identically except that ADDC adds the value of operand as well as the value of the Carry flag whereas ADD does not add the Carry flag to the result.8052 Instruction Set Definitions: Instruction: Indicates the correct syntax for the given opcode. leaving the resulting value in the Accumulator. if the unsigned summed value of the Accumulator. ACALL pushes the address of the instruction that follows ACALL onto the stack.

but not both." If operand refers to a bit of an output port. Bits 3-7 of the most-significant-byte of the Program Counter remain unchaged. and replacing bits 0-2 of the mostsignificant-byte of the Program Counter with bits 5-7of the opcode value.operand2 ANL does a bitwise "AND" operation between operand1 and operand2. If the register is a bit (including the carry bit). jumps may only be made to code located within the same 2k block as the first byte that follows AJMP. the value that will be complemented is based on the last value written to that bit. The value of operand2 is not affected. AJMP .operand2. operand and (in the case of ADDC) the Carry flag treated as signed values results in a value that is out of the range of a signed byte (-128 through +127) the Overflow flag is set. . Otherwise. This can be thought of as "Accumulator Logical Exclusive OR 255" or as "255-Accumulator.Auxillary Carry flag is cleared. Compare and Jump if Not Equal Syntax: CJNE operand1. If the two operands are equal program flow continues with the instruction following the CJNE instruction. ANL . A logical "AND" compares the bits of each operand and sets the corresponding bit in the resulting byte only if the bit was set in both of the original operands. otherwise the resulting bit is cleared. Clearing the accumulator sets the Accumulator. leaving the result in operand. otherwise it is cleared. CPL . only the specified bit is affected. Clear Register Syntax: CLR register CLR clears (sets to 0) all the bit(s) of the indicated register. If operand is the Accumulator then all the bits in the Accumulator will be reversed. If operand is a single bit then the state of the bit will be reversed. Since only 11 bits of the Program Counter are affected by AJMP.reladdr CJNE compares the value of operand1 and operand2 and branches to the indicated relative address if the two operands are not equal. not the last value read from it. CLR . if the addition of the Accumulator. the Overflow flag is cleared. Complement Register Syntax: CPL operand CPL complements operand. leaving the resulting value in operand1. Absolute Jump within 2k Block Syntax: AJMP codeAddress AJMP unconditionally jumps to the indicated codeAddress. The Carry bit (C) is set if operand1 is less than operand2. CJNE . In other words.s value to 0. Bitwise AND Syntax: ANL operand1. The Overflow (OV) bit is set if there is a carry-out of bit 6 or out of bit 7. The new value for the Program Counter is calculated by replacing the least-significant-byte of the Program Counter with the second byte of the AJMP instruction.

Increment Reister Syntax: INC register INC increments the value of register by 1. If the bit is not set program execution continues with the instruction following the JB instruction. The Overflow flag (OV) is set if division by 0 was attempted. otherwise it is cleared. Decimal Adjust Accumulator Syntax: DA A DA adjusts the contents of the Accumulator to correspond to a BCD (Binary Coded Decimal) number after two BCD numbers have been added by the ADD or ADDC instruction. In the case of "INC DPTR". incrementing the value will cause it to reset to 0. If the initial value of register is 0. If the carry bit is set or if the value of bits 0-3 exceed 9. otherwise it is cleared. If the initial value of register is 255 (0xFF Hex). decrementing the value will cause it to reset to 255 (0xFF Hex). INC . incrementing the value will cause it to reset to 0. Decrement and Jump if Not Zero Syntax: DJNZ register. Note: The Carry Flag is not set when the value "rolls over" from 255 to 0. If the carry bit was set when the instruction began. If the initial value of register is 0. JB . DIV . The Carry bit (C) is set if the resulting value is greater than 0x99. decrementing the value will cause it to reset to 255 (0xFF Hex). The resulting quotient is placed in the Accumulator and the remainder is placed in the "B" register. The Carry flag (C) is always cleared. or if 0x06 was added to the accumulator in the first step.relAddr DJNZ decrements the value of register by 1. the two-byte value of DPTR is incremented as an unsigned integer. Note: The Carry Flag is not set when the value "rolls over" from 0 to 255. Decrement Register Syntax: DEC register DEC decrements the value of register by 1. Jump if Bit Se t Syntax: JB bitAddr. Again. . DEC . If the initial value of DPTR is 65535 (0xFFFF Hex). program flow continues with the instruction following the DJNZ instruction.relAddr JB branches to the address indicated by relAddr if the bit indicated by bitAddr is set. the Carry Flag is not set when the value of DPTR "rolls over" from 65535 to 0. DJNZ . Divide Accumulator by B Syntax: DIV AB Divides the unsigned value of the Accumulator by the unsigned value of the "B" register.DA . If the new value of register is not 0 the program will branch to the address indicated by relAddr. 0x06 is added to the accumulator. If the new value of register is 0. 0x60 is added to the accumulator.

causing program execution to continue at that address. Long Cal l Syntax: LCALL address16 LCALL calls a program subroutine. If the bit is set program execution continues with the instruction following the JNB instruction. JNB . Jump to Data Pointer + Accumulator Syntax: JMP @A+DPTR JMP jumps unconditionally to the address represented by the sum of the value of DPTR and the value ofthe Accumulator. If the value of the Accumulator is non-zero program execution continues with the instruction following the JNZ instruction. Jump if Bit Not Set Syntax: JNB bitAddr. Jump if Carry Se t Syntax: JC relAddr JC will branch to the address indicated by relAddr if the Carry Bit is set. Before branching to relAddr the instruction will clear the indicated bit. Jump if Carry Not Set Syntax: JNC reladdr JNC branches to the address indicated by relAddr if the carry bit is not set. JNZ .JBC . JNC . Jump if Bit Set and Clear Bit Syntax: JBC bitAddr. If the Carry Bit is not set program execution continues with the instruction following the JC instruction. Jump if Accumulator Not Zero Syntax: JNZ reladdr JNZ will branch to the address indicated by relAddr if the Accumulator contains any value except 0. JZ .reladdr JNB will branch to the address indicated by relAddr if the indicated bit is not set.relAddr JBC will branch to the address indicated by relAddr if the bit indicated by bitAddr is set. Jump if Accumulator Zero Syntax: JZ reladdr JZ branches to the address indicated by relAddr if the Accumulator contains the value 0. The Program Counter is then set to the 16-bit value address16. If the bit is not set program execution continues with the instruction following the JBC instruction and the value of the bit is not changed. If the value of the Accumulator is zero program execution continues with the instruction following the JNZ instruction. . low-byte first. JC . LCALL . LCALL increments the program counter by 3 (to point to the instruction following LCALL) and pushes that value onto the stack . If the carry bit is set program execution continues with the instruction following the JNB instruction. high-byte second. JMP .

LJMP .operand2 MOVX moves a byte to or from external memory into or from the Accumulator. Move into/out of Carry Bit Syntax: MOV bit1. the operand bytes of the instruction are stored in reverse order. 20h. The value of operand2 is not affected. MOV . NOTE: In the case of "MOV direct1. If operand2 is @R0 or @R1 then the byte is moved from external memory into the Accumulator. This instruction uses both P0 (port 0) and P2 (port 2) to output the 16-bit address and data.#data16 Instructions OpCode Bytes Cycles Flags MOV DPTR. Either bit1 or bit2 must refer to the Carry bit. P2 (port 2) is not affected.operand2 operand1. This instruction uses only P0 (port 0) to output the 8-bit address and data. the Accumulator is moved to the 8-bit external memory address indicated by the specified register. Long Jump Syntax: LJMP address16 LJMP jumps unconditionally to the specified address16. If operand1 is @DPTR. If operand2 is DPTR then the byte is moved from external memory into the Accumulator. 50h means "Move the contents of Internal RAM location 0x20 to Internal RAM location 0x50" whereas the opposite would be generally presumed. the instruction consisting of the bytes 85h. That is. The value of operand2 is not affected. Move Code Byte to Accumulator Syntax: MOVC A.@A+register MOVC moves a byte from code memory into the Accumulator.direct2 ".bit2 MOV copies the value of bit2 into bit1. MOV DPTR . MOV . In the case of the Program Counter. Move value into DPTR Syntax: MOV DPTR. The value of bit2 is not affected. . operand2 MOV copies the value of operand2 into operand1. The code memory address from which the byte will be moved is calculated by summing the value of the Accumulator with either DPTR or the Program Counter (PC). MOVC . If operand1 is @R0 or @R1. MOV . Move into/out of Internal RAM Syntax: MOV operand1. Move Data to/from External RAM Syntax: MOVX operand1. the Accumulator is moved to the 16-bit External Memory address indicated by DPTR. PC is first incremented by 1 before being summed with the Accumulator. MOVX .#data16 0x90 3 2 None Sets the value of the Data Pointer (DPTR) to the value data16. Move Memory into/out of Accumulator Syntax: MOV operand1.

No Operation Syntax: NOP NOP. etc.s name suggests. NOP is generally used only for timing purposes. you must pop the value into the accumulator and then move the value of the accumulator into R0. The Carry Flag (C) is always cleared. otherwise it is cleared. The latter is invalid and will result in an error at assembletime. Bitwise OR Syntax: ORL operand1. such as R0. NOTE #2: When popping a value off the stack into the Accumulator. not POP A. leaving the resulting value in operand1. registers. causes no operation to take place for one machine cycle. etc. you must code the instruction as POP ACC. In other words. PUSH first increments the value of the Stack Pointer by 1. Pop Value from Stack Syntax: POP register POP "pops" the last value placed on the stack into the direct address specified. The value of operand2 is not affected. To push a value onto the stack . Absolutely no flags or registers are affected. Push Value onto Stack Syntax: PUSH register PUSH "pushes" the value of the specified direct address onto the stack. The stack pointer is then decremented by 1. You cannot PUSH directly from .R. POP . otherwise the resulting bit is cleared. PUSH . The leastsignificant byte of the result is placed in the Accumulator and the mostsignificant-byte is placed in the "B" register.operand2 ORL does a bitwise "OR" operation between operand1 and operand2. R1. NOTE #1: The address of direct must be an Internal RAM or SFR address. as it.MUL . NOTE #1: The address of direct must be an Internal RAM or SFR address. A logical "OR" compares the bits of each operand and sets the corresponding bit in the resulting byte if the bit was set in either of the original operands. R1. ORL . To pop a value off the stack into R0. You cannot POP directly into .R. such as R0. POP will load direct with the value of the Internal RAM address pointed to by the current Stack Pointer. The Overflow Flag (OV) is set if the result is greater than 255 (if the most-significant byte is not zero). then takes the value stored in direct and stores it in internal RAM at the location pointed to by the incremented Stack Pointer. registers. Multiply Accumulator by B Syntax: MUL AB Multiplies the unsigned value in the Accumulator by the unsigned value in the "B" register. NOP . for example.

RETI . The latter is invalid and will result in an error at assemble-time. RET . RR . The left-most bit (bit 7) of the Accumulator is loaded into bit0. followed by the least-significant-byte. The most-significant-byte is popped off the stack first. and the original Carry Flag is loaded into bit 7. NOTE #2: When pushing a value from the accumulator onto the stack into the. Rotate Accumulator Left Syntax: RL A Shifts the bits of the accumulator to the left. RETI functions identically to RET if it is executed outside of an interrupt service routine. followed by the least-significant-byte. Return from Subroutine Syntax: RET RET is used to return from a subroutine previously called by LCALL or ACALL. Program execution continues at the address that is calculated by popping the top-most 2 bytes off the stack. The left-most bit (bit 7) of the accumulator is loaded into the Carry Flag. Rotate Accumulator Right Through Carry Syntax: RRC A Shifts the bits of the accumulator to the right. RRC . Rotate Accumulator Righ t Syntax: RR A Shifts the bits of the accumulator to the right. The right-most bit (bit 0) of the accumulator is loaded into the Carry Flag. and the original Carry Flag is loaded into bit 0 of the Accumulator.byte is popped off the stack first. . not PUSH A. RL . The right-most bit (bit 0) of the accumulator is loaded into bit 7. Program execution continues at the address that is calculated by popping the top-most 2 bytes off the stack. RETI first enables interrupts of equal and lower priorities to the interrupt that is terminating. The mostsignificant. then PUSH the value of the accumulator onto the stack. Rotate Accumulator Left Through Carry Syntax: RLC A Shifts the bits of the accumulator to the left.from R0. Return from Interrupt Syntax: RETI RETI is used to return from an interrupt service routine. you must code the instruction as PUSH ACC. you must move R0 into the accumulator. RLC . for example.

XRL . otherwise it is cleared. The Carry Bit (C) is set if a borrow was required for bit 7. In other words. Set Bi t Syntax: SETB bitAddr Sets the specified bit.SETB . This instruction is identical to executing "RR A" or "RL A" four times. but not both. The Auxillary Carry (AC) bit is set if a borrow was required for bit 3. Exchange Bytes Syntax: XCH A. Exchange Digi t Syntax: XCHD A. Otherwise it is cleared. the bit is set if the low nibble of the value being subtracted was greater than the low nibble of the accumulator. the assembler will automatically use the 0xD3 opcode. SJMP . XCHD . if the unsigned value being subtracted is greater than the accumulator the carry flag is set. If any other bit is set. leaving the resulting value in operand1. RelAddr must be within 128 or +127 bytes of the instruction that follows the SJMP instruction.register Exchanges the value of the accumulator with the value contained in register. the subtraction of two signed bytes resulted in a value outside the range of a signed byte (-128 to 127). Bits 4-7 of each register are unaffected. XCH . Bitwise Exclusive OR Syntax: XRL operand1. The value operand is not affected. Short Jump Syntax: SJMP relAddr SJMP jumps unconditionally to the address specified relAddr.operand2 XRL does a bitwise "EXCLUSIVE OR" operation between operand1 and operand2.register Exchanges bits 0-3 of the accumulator with bits 0-3 of the Internal RAM address pointed to indirectly by R0 or R1. SUBB . Subtract from Accumulator with Borrow Syntax: SUBB A. otherwise it is cleared. In other words. If the instruction requires the Carry bit to be set. SWAP .operand SUBB subtracts the value of operand from the value of the accumulator. the assembler will automatically use the 0xD2 opcode. A logical . The Overflow (OV) bit is set if a borrow was required for bit 6 or for bit 7. In other words. leaving the resulting value in the accumulator. Subtract Accumulator Nibbles Syntax: SWAP A SWAP swaps bits 0-3 of the Accumulator with bits 4-7 of the Accumulator. The value of operand2 is not affected.

conditional branching instructions. Conditional branching is the fundamental building block of program logic since all "decisions" are accomplished by using conditional branching. Direct Jumps While conditional branching is extremely important. The obvious difference between the Direct Jump and Call instructions and the conditional branching is that with Direct Jumps and Calls program flow always changes. the JB instruction. can cause the program flow to deviate from its otherwise sequential scheme."EXCLUSIVE OR" compares the bits of each operand and sets the corresponding bit in the resulting byte if the bit was set in either (but not both) of the original operands. THEN" structure in 8052 assembly language. If the bit is not set the conditional branch fails and program execution continues. otherwise the bit is cleared. Program Flow When an 8052 is first initialized the PC SFR is reset to 0000h.128 bytes of the memory address that contains the conditional branching instruction. skipping the NOP instruction. Take. when enabled. specifically. This is accomplished in the 8052 using "Direct Jump and Call" instructions. as a group. it is often necessary to make a direct branch to a given memory location without basing it on a given logical decision. An important note worth mentioning about conditional branching is that the program may only branch to instructions located within 128 bytes prior to or 127 bytes after the address that follows the conditional branch instruction. for example. These instructions cause program execution to follow a nonsequential path if a certain condition is true. and "returns" from subroutines. There are various instructions that can modify the value of the PC." When the 8052 executes this instruction the PC is loaded with the address of NEW_ADDRESS and program execution continues sequentially from there.. Conditional branching can be thought of as the "IF. This means that in the above example the label HELLO must be within +/. Conditional Branching The 8052 contains a suite of instructions which.. with the NOP instruction that follows." An example of the JB instruction might be: In this case. are referred to as "conditional branching" instructions. s illustrated in the last paragraph. The 8052 then begins to execute instructions sequentially in memory unless a program instruction causes the PC to be otherwise altered. the 8052 will analyze the contents of bit 45h. If the bit is set program execution will jump immediately to the label HELLO. as usual. This instruction means "Jump if Bit Set. With conditional branching program flow only . This is equivalent to saying "GOTO" in BASIC. In this case you want the program flow to continue at a given memory address without considering any conditions. Consider the example: The LJMP instruction in this example means "Long Jump. interrupts. direct jumps and calls. this suite of instructions causes program flow to change unconditionally. Additionally.

can only jump to an address within +/.changes if a certain condition is true.range. there are two other instructions that cause a direct jump to occur: the SJMP and AJMP commands. They both have limitations as to the . like the conditional branching instructions. if the AJMP command is at code memory location 650h. these two commands perform the exact same function as the LJMP command--that is to say. Similar in format to the AJMP instruction that was described in the previous section. Returns from Routines Another structure that can cause program flow to change is the "Return from Subroutine" instruction. known as RET in 8051 Assembly Language. but is variable in the sense that where program flow continues can be different each time the RET instruction is executed depending on from where the subroutine was called originally. You may ask yourself. The SJMP command. However. It is worth mentioning that. 2. they always cause program flow to continue at the address indicated by the command. More accurately. If you are developing an application that has memory restrictions you can often save quite a bit of memory using the 2-byte AJMP/SJMP instructions instead of the 3-byte instruction. . 1. The RET command is direct in the sense that it always changes program flow without basing it on a condition. Functionally. when executed. of the jumps. these instructions differ from LJMP in that they are not capable of jumping to any address.128 bytes of the SJMP command. it returns to the address that is stored on the stack. "Why would I want to use the SJMP or AJMP command which have restrictions as to how far they can jump if they do the same thing as the LJMP command which can jump anywhere in memory?" The answer is simple: The LJMP command requires three bytes of code memory whereas both the SJMP and AJMP commands require only two. the ACALL instruction provides a way to perform the equivalent of an "LCALL" with a 2byte instruction (instead of 3) as long as the target routine is within the same 2k block of memory. The RET instruction. it can only do a jump to addresses 0000h through 07FFh (0 through 2047. decimal). returns to the address following the instruction that called the given subroutine. That is to say. The AJMP command can only jump to an address that is in the same 2k block of memory as the AJMP command. aside from LJMP. Direct Calls Another operation that will be familiar to seasoned programmers is the LCALL instruction. When the 8052 executes an LCALL instruction it immediately pushes the current Program Counter onto the stack and then continues executing code at the address indicated by the LCALL instruction.

Interrupts An interrupt is a special feature that allows the 8052 to break from its normal program flow to execute an immediate task, providing the illusion of "multi-tasking." The word "interrupt" can often be substituted with the word "event." An interrupt is triggered whenever a corresponding event occurs. When the event occurs, the 8052 temporarily puts "on hold" the normal execution of the main program and executes a special section of code referred to as the "Interrupt Service Routine" (ISR). The ISR performs whatever special functions are required to handle the event and then returns control to the 8052 at which point program execution continues as if it had never been interrupted. The topic of interrupts is somewhat tricky and very important. For that reason, an entire chapter will be dedicated to the topic. Instruction Set, Timing, and Low-Level Information In order to understand--and better make use of--the 8052, it is necessary to understand some underlying information concerning timing. The 8052 operates with timing derived from an external crystal or a clock signal generated by some other system. A crystal is a component that allows an electronic oscillator to run at a very precisely known frequency. One can find crystals of virtually any frequency depending on the application requirements. When using an 8052, one of the most common crystal frequencies is 11.0592 megahertz. Why would anyone pick such an oddball frequency? There.s a reason which has to do with generating baud rates and we.ll talk more about it in the Serial Communication chapter. For the remainder of this discussion we.ll assume that we.re using an 11.0592Mhz crystal. Microcontrollers (and many other electrical systems) use their oscillators to synchronize operations. The 8052 uses its crystal or clock for precisely that: to synchronize its internal operation. The 8052 operates using what are called "instruction cycles." A single instruction cycle is the minimum amount of time in which a single 8052 instruction can be executed, although many instructions take multiple cycles. A cycle is, in reality, 12 clock cycles from the crystal. That is to say, if an instruction takes one instruction cycle to execute, it will take 12 clocks of the crystal to execute. Since we know the crystal oscillates 11,059,200 times per second and that one instruction cycle is 12 clock cycles, we can calculate how many instruction cycles the 8052 can execute per second: 11,059,200 / 12 = 921,600 This means that the 8052 can execute 921,600 single-cycle instructions per second. Since a large number of 8052 instructions are single-cycle instructions it is often considered that the 8051 can execute roughly 1 million instructions per second (MIPS), although in reality it is less--and, depending on the instructions being used, an estimate of about 600,000 instructions per second is more realistic. For example, if you are using exclusively 2-cycle instructions you would find that the 8052 executes 460,800 instructions per second. The traditional 8052 also has two really slow instructions (MUL AB and DIV AB) that require a full 4 cycles to execute--if you were to execute nothing but those instructions you.d find performance to be about 230,400 instructions per second. It is again important to emphasize that not all instructions

execute in the same amount of time. The fastest instructions require one instruction cycle (12 clock cycles), many others require two instruction cycles (24 clock cycles), and the two very slow math operations require four instruction cycles (48 clock cycles). Since all the instructions require different amounts of time to execute, a very obvious question comes to mind: How can one keep track of time in a time-critical application if we have no reference to time in the outside world? NOTE: Many derivative chips change instruction timing. For example, many optimized versions of the 8052 execute instructions in 4 oscillator cycles instead of 12; such a chip would be effectively 3 times faster than the 8052 when used with the same 11.0592 MHz crystal. Counters and Timers It was mentioned in previous chapters that MCU clock employs quartz crystal. As this frequency is highly stable and accurate, it is ideal for time measuring (similar oscillators can be found in watches). To determine the amount of time past between two occurrences, all you need to do is count the generated impulses. This is where the timer takes part; properly programmed, value of timer register will increase or decrease with every MCU clock impulse. Since one instruction takes 12 oscillator cycles to complete, the math is easy. For example, if quartz oscillator works at 12 MHz, timer register will increase/decrease every microsecond (million times per second). AT89S52 has three timers/counters marked as T0, T1, and T2. Two of them are from the "first lineup" shared by all models from 8051 family, while the third (T2) was added in the process of developing the basic model. Their purpose is to measure time and count external occurrences, but can also be used as clock in serial connection, Baud Rate. Timer T0 As shown in the image below, T0 consists of two registers - TH0 and TL0, for storing higher and lower byte of a 16-bit binary numeral.

For example, if T0 = 0, both registers will have value of zero. If T0 has value of 1000 (decimal), TH0 (higher byte) will hold decimal value of 3, and TL0 (lower byte) will hold decimal value of 232. See the image below.

Formula for calculating the value of 16-bit register is simple: TH0 * 256 + TL0 = T On our previous example: 3 * 256 + 232 = 1000 Timers are technically 16-bit registers, thus the maximal value they can hold is 65.535. If this number is exceeded, timer will automatically reset and start from zero. This situation is known as overflow. Two registers tightly connected to Timer T0 are TMOD and TCON.

TMOD . There are 4 of these modes.bit7) are associated with T1.3) is set 0 Timer works regardless of INT1 (P3.7 : Bit 7 Bit Name GATE1 Purpose 1 Timer works only if INT1 (P3.3) 6 C/T1 1 Timer counts impulses on T1 (P3. The following table gives details on bits 0 .2) 2 C/T0 1 Timer counts impulses on T0 (P3. lower 4 bits (bit 0 .2) is set 0 Timer works regardless of INT0 (P3. As shown in the image below.4) 0 Timer counts impulses of internal oscillator 1 0 T0M1 T0M0 Timer mode Timer mode T0 T0 T0 T1 T1 T0 T1 Timer T1 Four bits from the previous table determine the operating mode of timers T0 and T1.bit 3) are associated with T0.Timer Mode This register sets mode for timers T0 and T1. and each will be covered in details. T0M1 T0M0 Mode Description 0 0 1 0 1 0 0 1 2 13-bit Timer 16-bit Timer 8-bit auto-reload .5) 0 Timer counts impulses of internal oscillator 5 4 3 T1M1 T1M0 GATE0 Timer mode Timer mode 1 Timer works only if INT0 (P3. while the higher 4 bits (bit4 .

. Mode 1 (16-bit Timer) Mode 1 uses all bits of registers TH0 and TL0. except the timer reaches value of 65. upon which both registers are reset to zero. How does it work? On each impulse. lower register is changed (the "trimmed" one). with Mode 0.1 1 3 Split mode Mode 0 (13-bit Timer) This mode is an antiquity kept just for the sake of compatibility with older MCUs. This process repeats itself until 8192 impulses are registered. it is automatically reset. When TL0 is filled after 32 impulses. and is commonly used. Timer T0 uses only 13 of its 16 bits. When activated. whole higher byte TH0 and only the first 5 bits of lower byte TL0 are accessible. Thus. Counting process is same as with Mode 0.536 (max for 16 bits) before reset. and TH0 is increased by one.

In this mode. Advantages of this mode will be illustrated on the following example: suppose that there is a need to report every 55th impulse of the clock. however. instead of reset. Namely. registers TH0 and TL0 act as separate 8-bit timers: TH0 substitutes Timer 0. you would need to store 200 (decimal) into T0. Thus. only one of two registers is used for counting. MCU performs this task automatically. it will load value from TH0. while TH0 stores the starting value. Mode 3 ("Split" Timer) When Timer T0 is configured to Mode 3. Upon hit. In Mode 2. and set the Timer Mode 2. but from a specified value stored in the other register (0-255). specifically 200 in our example. If Mode 0 or Mode 1 was used. When TL0 is filled. TL0 works as an 8-bit timer. to register every 55th impulse. all you need to do is write 200 to TH0. value of 200 would need to be written to T0 again. and then continually check for the overflow (exceeding 255 decimal). while . you actually get an additional timer. it does not start from zero.Mode 2 (8-bit "auto reload" Timer) What is "auto reload" ? Simply.

Bit 7 Bit Name TF1 Purpose Timer This bit is automatically set in T1 case of overflow in Timer T1 6 TR1 1 .Timer T1 is on 0 .Timer T0 is off T0 Starting Timer T0 Select this timer and set the desired mode. This means that. 2.Timer T1 is off T1 5 TF0 This bit is automatically set in T0 case of overflow in Timer T0 4 TR0 1 .Timer T0 is on 0 . it will be constantly active in the background. although it can be set to any mode (Mode 1. . TCON . while the other 4 are associated with interrupts. Consequently. all control bits associated with the original Timer 1 (16-bit register consisting of TH1 and TL1) are now in control of newly created "Timer 1". because there is simply no control bit to do it. the original Timer 1 cannot be stopped anymore.Timer Control TCON is another register in direct control of the timers.TL0 substitutes Timer 1. In this mode. Of the 8 bits. or 3). TCON uses only 4 bits for controlling the timers.

as long as the bit TR0 is set. Assuming that 12MHz quartz crystal is installed.536 microseconds. MCU automatically resets them and the Timer continues the loop. . After passing of 65. Right after the command for setting the bit TR0. value in T0 will increase every microsecond. both registers of the Timer will be full. Timer is operational. and count the impulses of internal source with frequency equal to 1/12 of the quartz oscillator's frequency.This sets the Timer T0 to operate in Mode 1.

This widely inaccurate reading (255 impulses) may happen due to not so obvious.  Detection of Overflow Usually. There is also another solution: just turn off the Timer for the time of reading (clear the bit TR0 in TCON). When it happens. and then the higher byte again. there is no need to continually read the Timer registers. yet perfectly logical reason. the sequence has to be repeated (this is a mini-loop in the program. If two readings of higher byte do not match. This moment can be "awaited". changing both registers (TH0: 14 -> 15. TL0: 255 -> 0). Solution to the problem is simple: you need to read the higher byte first. but the true state of registers at the moment of reading was: TH0=14.  If you need to read the value of the Timer which uses only one register for counting (Mode 3. the results are valid. Seemingly. TL0=255. TL0=255. then the lower byte. you need to calculate a number to be written to Timer registers: . Lower byte was read ok (255). For example. reading is a bit more complicated. or by enabling an interrupt. it is sufficient to detect the moment at which they are reset. respectively: TH0=15.Reading Timer Depending on the application. the so-called Overflow. If the Timer works in Mode 2. bit TF0 in TCON will be automatically set. you need either the value written in Timer registers. not more than 3 instructions). and turn it on afterwards. but while the Program Counter was "loading" your new instruction for reading TH0. you might have obtained values of the lower and the higher byte. for example) just read the value of that register. by writing a small loop for testing the bit continually. overflow occurred. or the exact point of time at which the Timer is reset. Suppose that there is a need to suspend a program for duration of 0.05 seconds (5000 cycles): First.

Timer measures the time. i. 0. for example. Timer will work only for as long as the pin P3. Timer can measure the active period of the device. But. when started (bit TR0 = 1). if GATE0 = 1. Now a program instruction can be used to test if the bit TF0 was set. which was the original idea.2 is set.05 seconds.000 cycles.e. i.e. If bit is set.2 has no effect on the Timer. measuring for how long has device been active. Measuring Impulse Duration Measuring time past between two events is a common task in electronics. simultaneously with turning the power on. which should take place after exactly 50. impulses from P3. Similar to the previous example. Timer will continue the counting up from our written value. Note the bit named GATE0 (in TMOD Register) in the Timer schematics. impulses generated by MCU clock. This means that. If this bit is cleared. by bringing 5V externally to this bit. Counting Impulses The answer is in bit C/T0 in TCON Register.This value should be stored to Timer registers TH0 and TL0: After that. pin P3.4 (T0) are conducted to Timer's . C/T0 "brings in" an external signal: if bit is cleared.

It can fulfill same roles. Timer T1 This is the "twin brother" of Timer T0. these impulses cannot be used for measuring time. it is also controlled by TMOD and TCON. The highest frequency this Counter can record equals 1/24 of frequency of used quartz-crystal. Having no predetermined order or sequence. effectively turning the Timer into Counter. . and has 4 different modes of work.input.

with numerous checks performed at strictly defined pace. and the same register accepts data from the line. better known as serial port. SCON (Serial Port Control Register) Bit Name SM0 SM1 SM2 REM Bit Address 9Fh 9Eh 9Dh 9Ch Purpose Mode of work Mode of work Enables connecting multiple MCU's When set. and the source of impulses for synchronization. Without it. SFR register SCON (Serial Control) is in control of the transfer parameters: size of one serial "word" in bits. Before using the serial port. baud rate. enables receiving data .Serial communication UART (Universal Asynchronous Communication) One of the things that makes this MCU so powerful is the hardware integrated UART. It is a duplex port capable of sending and receiving data simultaneously. it should be appropriately configured. serial data transfer would be an endlessly complicated task. UART represents an elegant solution: programmer just needs to set the mode and the rate of transfer. Controller takes care of all the details of transfer with no room for error. Register SBUF holds data to be sent to line.

and can be adjusted in modes 1 and 3 (details can be found in the chapter on timers). baud rate in modes 1.TB8 RB8 TI 9Bh 9Ah 99h 9th bit for sending data in modes 2 and 3 9th bit for sending data in modes 2 and 3 Bit is automatically set when the whole byte is sent RI 98h Bit is automatically set when the whole byte is received As shown in the table. but serves to provide additional I/O pins. Although there is no limit on the number of I/O ports that can be gained in this manner. combination of bits SM0 and SM1 determines the mode of work for serial port: SM0 0 0 1 1 SM1 0 1 0 1 Mode Description 0 1 2 3 8-bit Shift register 8-bit UART 9-bit UART 9-bit UART Baud Rate Quartz frequency / 12 Determined by timer T1 or T2 Quartz frequency / 32 Determined by timer T1 or T2 Obviously. which is then serially transferred to the controller. . In addition. baud rate in modes 0 and 2 is fixed. 2. making this mode rarely used. Mode 0 Mode 0 is not used for standard serial communication. External shift registers convert the data into binary sequence. and 3 is doubled if bit SMOD in register PCON is set (see below). the existing 32 I/O lines are sufficient for most of the tasks.

it stores value of the ninth bit. Otherwise. it needs to be cleared to provide normal functioning of the communication REN TB8 RB8 Needs to be set to enable receiving data via serial communication Auxiliary 9th bit in 9-bit transfer (modes 2 and 3) Similar to TB8. but on receiving. In this way. and to the bit RB8 after transfer. followed by 8 data bits (LSB bit is first). followed by 8 data bits (LSB bit is first). . When accepting 9-bit data. this "raw" serial data needs to be inverted this is carried out automatically by the designated drivers. but on receiving. Start bit is not registered anywhere as its sole purpose is to start the mechanism for receiving data. processor "knows" that the line is free for sending another byte. Modes 2 and 3 These modes are frequently used for speedy transfers at short range (Mode 2) and for standard RS-232 transfers with parity bit (Mode 3). RI Similar to TI. Other bits of register SCON have following roles: Bit SM2 Purpose This bit is used if multiple microcontrollers exchange data using the same line. TI This bit is automatically set when the last bit of one byte has been proceeded to the line. and that it should be read before another one arrives. Both modes transfer 9-bit data in the following order: one start bit (always 0). It is a "doorbell" of a kind. stop bit is automatically copied to bit RB8 in register SCON. and one stop bit (always 1). and finally one stop bit (always 1). Sequence of ten bits is sent via pin TXD or received via pin RXD in the following order: one start bit (always 0). When data is received. 9th bit which is copied from the bit TB8 before transfer.Mode 1 This is the standard RS-232 mode for serial transfer of 8-bit data. which indicates that one byte has been received. In order to connect the controller to RS-232 line.

rate is determined by the frequency of overflow occurrence. Crystals designed specifically for this purpose can be found in the market. If timer T2 is used for setting the Baud Rate. and can be calculated according to the formula: Quartz oscillator frequency Baud Rate = 384 * (256 . allowing the microcontroller to send and receive data at different rates: RCLK TCLK Mode of work . rate will be doubled: Quartz oscillator frequency Baud Rate = 192 * (256 . 11. Baud Rate in modes 0 and 2 depends solely on the frequency of quartz crystal. Although their frequencies might seem a bit exotic at first (e. In this case.TH1) Here.g. you need to set the Baud Rate. and should be cleared to avoid causing an interrupt. they produce standard rates for serial communication after the clock has been divided by the controller.059 MHz). its bits will always have priority.TH1) If bit SMOD in register PCON is set. bits which are automatically set upon overflow are of no use. Timer T1 is most commonly used in "Auto-Reload" mode (TMOD = 0010xxxx). Baud Rate in modes 1 and 3 is determined by timers T1 and/or T2.Setting the Baud Rate Once you have selected the mode of UART.

Similar procedure takes place when receiving data . you just need to read the register SBUF. . sending rate is set by T1 Rates of sending and receiving are equal and set by timer T2 only Sending and Receiving Data via UART Once UART is prepared for transfer. MCU starts sending it. As soon as data is written to this port. sending and receiving data is very simple. bit TI in register SCON is set to indicate that one byte has been sent.after the bit RI (also in SCON) has been set. sending rate is set by T2 Receiving rate is set by T2. It all comes down to simple writing and reading of register SBUF.0 0 Rates of sending and receiving are equal and set by timer T1 only 0 1 1 1 0 1 Receiving rate is set by T1. one bit at a time. At the end of the sequence.

as shown in the figure below. Each of these interrupts can be individually enabled or disabled by configuring the register IE. If these two bits are cleared. Namely. but in this case it will be continually executed as long as the state on pins is low. on falling edge of the impulse. same signal will trigger an interrupt. program will be interrupted on change of pins from 1 to 0. i. There is one not so obvious detail which requires an additional explanation. if bits IT0 and IT1 (in register TCON) are set. Also. and it concerns the external interrupts .e. meaning that it can recognize up to 6 different events that can interrupt regular program execution.INT0 and INT1. IE (Interrupt Enable) . whole system of interrupts can be disabled by clearing the bit EA in the same register.Interrupts AT89S51 supports total of 6 interrupt sources.

Our microcontroller can differentiate between three priority levels: 1. 3. Priority 2 interrupts. Priority 1 interrupts. If multiple interrupts are enabled. based on a priority check. In such cases. controller needs to resolve whether to proceed with the current interrupt routine. Can be interrupted only by reset. Can be interrupted by any of above.logical state of 1 enables the appropriate interrupt): Bit EA ET2 ES ET1 EX1 ET0 EX0 Purpose Enables/disables all interrupt sources Timer T2 interrupt UART and SPI interrupts Timer T1 interrupt External interrupt: pin INT1 Timer T0 interrupt External interrupt: pin INT0 Interrupt Priorities It cannot be predicted with absolute certainty when will interrupt request take place. all processes are halted and the controller behaves as if the power had just been turned on. Reset.Following table describes the bits of register IE (same rule applies to all bits . or to enter a new one. If there is a request for reset. IP (Interrupt Priority) . it's quite possible to have interrupt requests during execution of another interrupt routine. 2.

Current instruction is executed first. Depending on the interrupt in question. Address of the instruction that would be executed next if there was no interrupt request is put away to stack. If both interrupts are of same priority. 3. How does interrupt execute? Upon receiving an interrupt request. 2. program counter will take value of one of possible 6 vectors (addresses) according to the table below. the one with the later request has to hold one and let the controller handle the first one. Interrupt source IE0 TF0 Vector (address in hex) 0003h 000Bh . following scenario takes place: 1. the one with higher priority has precedence in execution.SFR register IP determines the priority of existing interrupt sources (Same rule applies to all bits : logical state of 1 assigns higher priority to the appropriate interrupt): Bit PT2 PS PT1 PX1 PT0 PX0 Purpose Timer T2 interrupt priority Serial port interrupt priority Timer T1 interrupt priority External interrupt INT1 priority Timer T0 interrupt priority External interrupt INT0 priority If two interrupt requests collide.

One of the most common devices attached to an 8051 is an LCD display. an 8051 program must interact with the outside world using input and output devices that communicate directly with a human being. (ii) Ease of programming for characters and graphics. which refers to the controller chip which receives data from an external source (in this case. address of the next instruction to be executed is retrieved from the stack. These addresses should hold the appropriate subroutines for handling the interrupts. This means 16 characters per line by 2 lines and 20 characters per line by 2 lines. TI. characters and graphics. This is in contrast to LEDs and 7-segment displays. LCD Interfacing: Frequently. 16x2 character LCD Fortunately. The standard is referred to as HD44780U. 5. Some of the most common LCDs connected to the 8051 are 16x2 and 20x2 displays. SPIF TF2. they only point to the location of appropriate routines in the code. respectively. instead of actual routines. Upon accomplishing the interrupt routine. and the program proceeds from the location where it was interrupted. which are limited to numbers and few characters. a very popular standard exists which allows us to communicate with the vast majority of LCDs regardless of their manufacturer. .IE1 TF1 RI. the 8051) and communicates directly with the LCD. EXF2 0013h 001Bh 0023h 002Bh 4. Why LCD’s are widely used: The widespread of using LCD’s is because of (i) The ability to display numbers. In practice.

L pulse The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus Vcc. The three control lines are referred to as RS. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Symbol Vss Vcc VEE RS R/W E DBO DB1 DB2 DB3 DB4 DB5 DB6 DB7 ---I I I/O I/O I/O I/O I/O I/O I/O I/O I/O I/O Description Ground +5V power supply Power supply to control contrast RS=0 to select command register RS=1to select data register R/W=0 for write R/W=1 for read Enable. Pin description of LCD. the LCD will require a total of 3 control lines plus the 8 lines for the data bus. the LCD will require a total of 7 data lines (3 control lines plus the 4 lines for the data bus). The user may select whether the LCD is to operate with a 4-bit data bus or an 8-bit data bus. H. Pin NO. When RS is low (0). RW and EN.44780 standards: The 44780 standard requires 3 control lines as well as either 4 or 8 I/O lines for the data bus. Vee is used for controlling LCD contrast. etc. Vss and VEE: Vcc and Vss provide +5v and ground. If an 8-bit data bus is used. respectively. . Register select: There are very two important registers inside the LCD.). the data is to be treated as a command or special instruction (such as clear screen. position cursor. RS. The RS pin is used for their selection as follows. If a 4-bit data bus is used. The RS line is the "Register Select" line.

Finally. the data bus consists of 4 or 8 lines (depending on the mode of operation selected by the user). the program is effectively querying (or reading) the LCD. Only one instruction ("Get LCD status") is a read command. to set the RW line high (1). we are going to equate constants to the 8051 ports so that we can refer to the lines by their names as opposed to P0. you must always manipulate EN when communicating with the LCD.2. DB2.When RS is high (1). All others are write commands--so RW will almost always be low. the information on the data bus is being written to the LCD. In the case of an 8-bit data bus. we've established a 1-to-1 relation between a pin on the 8051 and a line on the LCD. DB3. the data being sent is text data which should be displayed on the screen." This control line is used to tell the LCD that you are sending it data. A high to low transition tells the LCD to take the data currently found on the other control lines and on the data bus and to treat it as a command. we may now refer to our I/O lines by their name. The EN line is called "Enable. and DB7. we can execute the following instruction: SETB RW SETB RS SETB EN HANDLING THE EN CONTROL LINE As we mentioned above. The RW line is the "Read/Write" control line. your program should first set this line high (1) and then set the other two control lines and/or put data on the data bus. to display the letter "T" on the screen you have to set RS high. When the other lines are completely ready. Note that the EN line must be raised/lowered before/after each instruction sent to the LCD regardless of whether that instruction is read or write text or instruction. P0. In short. bring EN low (0) again. AN EXAMPLE HARDWARE CONFIGURATION A sample schematic of how the LCD will be connected to the 8051 is as follows: As you can see. When RW is high (1). DB6. Let's go ahead and write our initial equates: Having established the above equates. the lines are referred to as DB0. DB1. DB4. For example. etc.1. the EN line is used to tell the LCD that you are ready for it to execute an instruction that you've prepared on the data bus and on the other control lines. For example. When RW is low (0). EN is the LCD's . Thus as we write our assembly program to access the LCD. To send data to the LCD. DB5. The high to pulse must be minimum of 450ns wide.

CHECKING THE BUSY STATUS OF THE LCD As previously mentioned. it takes a certain amount of time for each instruction to be executed by the LCD. While it is possible to write code that waits for a specific amount of time to allow the LCD to execute instructions. Additionally. the program will not work until it is properly modified. when we issue the "Get LCD Status" command the LCD will immediately raise DB7 if it's still busy executing a command or lower DB7 to indicate that the LCD is no longer occupied. If the crystal frequency is changed. Additionally. Thus our program can query the LCD until DB7 goes low. although 44780 compatible. the LCD doesn't know you're talking to it on the other lines. the information that is useful to us right now is found in DB7. it is useful to make it a subroutine. your instruction will never be executed. At that point we are free to continue and send the next command. The "Get LCD Status" command will return to us two tidbits of information. the software will need to be modified. this method of "waiting" is not very flexible. The time it requires to execute an instruction depends on the instruction and the speed of the crystal which is attached. If you never bring EN low. indicating the LCD is no longer busy. In summary. Since we will use this code every time we send an instruction to the LCD. if the LCD itself is changed for another LCD which. . A more robust method of programming is to use the "Get LCD Status" command to determine whether the LCD is still busy executing the last instruction received. we'll always bring this line back low: CLR EN Programming Tip: The LCD interprets and executes our command at the instant the EN line is brought low. Let's write the code: Thus. The delay varies depending on the frequency of the crystal attached to the oscillator input of the LCD as well as the instruction which is being executed. before we interact in any way with the LCD we will always bring the EN line high with the following instruction: SETB EN And once we've finished setting up our instruction with the other control lines and data bus lines. it requires a certain amount of time to execute the command.way of knowing that you are talking to it. Thus. our standard practice will be to send an instruction to the LCD and then call our WAIT_LCD routine to wait until the instruction is completely executed by the LCD. If you don't raise/lower EN. requires more time to perform its operations. when you bring EN low and the LCD executes your instruction.

the program would not lock up." waiting for DB7 to go low. a maximum of 256 attempts to wait for the busy signal to go low. to send this 38h command to the LCD we must execute the following 8051 instructions: So. Of course. Programming Tip: The above routine does the job of waiting for the LCD. As you will recall from the last section. These two options are selected by sending the command 38h to the LCD as a command. it's always a good idea to do things yourself so that you can be completely sure that the display is the way you want it. it's a good idea to make it a subroutine: How that we've written a "Clear Screen" routine. if the LCD never becomes "not busy" the program will effectively "hang. INITIALIZING THE LCD Before you may really use the LCD. we may clear the LCD at any time by simply executing an LCALL CLEAR_LCD. but was it to be used in a real application a very definite improvement would need to be made: as written. Thus. we mentioned that the RS line must be low if we are sending a command to the LCD. This is accomplished by sending a number of initialization instructions to the LCD. this should never happen and won't happen when the hardware is working properly. the screen should automatically be cleared by the 44780 controller. Since clearing the screen is a function we very likely will wish to call more than once. However. our initialization code is as follows: Having executed this code the LCD will be fully initialized and ready for us to send display data to it. the program will freeze. This would guarantee that even if the LCD hardware fails. The first instruction we send must tell the LCD whether we'll be communicating with it with an 8-bit or 4-bit data bus.This will assure that our program gives the LCD the time it needs to execute instructions and also makes our program compatible with any LCD. in all. We also select a 5x8 dot character font. CLEARING THE DISPLAY When the LCD is first initialized. But in a real application it would be wise to put some kind of time limit on the delay--for example. it's not a bad idea to clear the screen as the very first operation after the LCD has been initialized. Thus. . Not surprisingly. An LCD command exists to accomplish this function. If this never happens. it is the command 01h. regardless of how fast or slow it is. you must initialize and configure it.

#'R' WRTDAT A. Consider: LCALL LCALL MOV LCALL MOV LCALL MOV LCALL MOV LCALL MOV LCALL MOV LCALL MOV LCALL MOV LCALL MOV LCALL MOV LCALL INIT_LCD CLEAR_LCD A. A "HELLO WORLD" PROGRAM Now that we have all the component subroutines written.#'D' WRTDAT . Once again.#'O' WRTDAT A. we're pretty much done. writing the classic "Hello World" program--which displays the text "Hello World" on the LCD. writing text to the LCD is something we'll almost certainly want to do over and over--so let's make it a subroutine. in turn.#'H' WRTDAT A.Programming Tip: Executing the "Clear Screen" instruction on the LCD also positions the cursor in the upper left-hand corner as we would expect.#'L' WRTDAT A. The WRTDAT routine that we just wrote will send the character in the accumulator to the LCD which will.#'L' WRTDAT A. display it.#'W' WRTDAT A. Really.#'L' WRTDAT A. WRITING TEXT ON TO THE LCD Now we get to the real meat of what we're trying to do: All this effort is really so we can display text on the LCD.#'O' WRTDAT A.#'E' WRTDAT A. is a relatively trivial matter. Thus to display text on the LCD all we need to do is load the accumulator with the byte to display and make a call to this routine.

i.e. When a switch is pressed a connection between the switch's row and the switch's column is made.16 switches arranged in 4 columns and 4 rows. clear the LCD screen. KEYPAD INTERFACING: The above diagram shows a 4 X 4 keypad . whenever a key is pressed the corresponding rows and columns are shorted. and display "Hello World" in the upper left-hand corner of the display. when executed. initialize the LCD.The above "Hello World" program should. . In the default state (all switches open) there is no connection between the rows and columns.

e. HERE: ACALL DELAY .'7' DB 0F7H.0 to P1.0B0H. Remember the port structure P1 has internal pull up resistors 3. make all the columns LOW MOV A.'2' DB 0FDH.70H.HERE .'3' DB 0FBH.#0F0H. P1.'4' DB 0F7H. Important steps in reading a keypad: Step1: See if any key is pressed .'5' DB 0FEH. KEYCHK: MOV PORT. If invalid go back to key scan mode The following coding shows the lookup table approach for storing the corresponding key data.70H. so keep scanning the key pad till a key is presses Step2: Once we have detected a key press we have to decode the key i.0B0H.7.if we find a key press the second time also.0D0H. check if there is key press SJMP KEYCHK The next subroutine checks whether the key press is due to noise or actual keypress. If no key is pressed you will read all rows as high.The lower nibble of Port1 i. Step3: We have to wait till the pressed key is released before We go on to process the next key During programming we have to remember the following things.'1' DB 0FEH. read port again to make sure it was not noise ANL A.'6' DB 0FDH. 1.PORT . This subroutine checks whether any key is pressed or not . read from the ports ANL A.#0F0H . Ground all the Columns and read the rows. KEYCODE: DB 0FEH.we can be assured that we have a valid key press.else we have to again go back to key scan mode.3 are Connected to the 4 columns The upper nibble is connected to the 4 Rows note that Row 1 is connected to P1.e we have to identify which key is pressed.70H.'9' DB 0FDH.70H. debounce MOV A.PORT .'0' DB 0FBH. 2.#0F0H.#0F0H CJNE A. mask the lower nibble CJNE A.0B0H.#0F0H .0B0H.'8' The following steps are required to find which key is pressed. Step1: Initialize pointer to Look Up Table . jump to decode the key SJMP KEYCHK .0D0H.KEYFIND . If some key is pressed then one of the rows will indicate a zero Note: But some times key press detected in the previous step could be due to noise or transients so in order to be sure that it is key press we need to do key debounce Key debounce involves giving a small delay of 20 ms and then checking again for a key press. If valid key.

read from the ports ANL A.@A+DPTR .in pointer and read input Step3: Input == Expected Input Key found exit loop Step4: Inc pointer to point to next code location and goto Step 2 The code for the above is as follows KEYFND: keyfnd1: MOV DPTR. Most all motors work on the electrical principle of induction. mask the lower nible CJNE A. When you put electric current through a wire. IN REG.PORT . between two magnets). check if there is keypress mov a.r3 lcall wrtdat sjmp keychk NEXT: KEYREL: MOTORS When trying to move things with microcontrollers. . get the first code into acc INC DPTR . R1 MOV A.Step2: Output code .KEYREL .NEXT INC DPTR .#0F0H . servomotors.#0F0H .A .A .IF KEY FOUND POINT TO THE CODE CLR A MOVC A. IN A CJNE A.#0F0H.#00H . and stepper motors.#00H MOVC A.#0F0H . PUT KEYCODE INTO PORT1 NOP NOP MOV A. the coil . READ FROM THE PORT ANL A. By placing a charged coil of wire in an existing magnetic field (say. it generates a magnetic field around the wire. LOAD THE EXPECTED NO. and in many good electronics and robotics books.A . MASK THE LOWER NIBBLE MOV R1.PORT . Following is a brief introduction to these three. #KEYCODE MOV A.01. there are basically three kinds of motors that are most useful: DC motors.STORE RESULT IN REG R3 SJMP KEYREL INC DPTR INC DPTR SJMP KEYFND 1 MOV PORT. make all the colums LOW MOV A. More notes can be found all over the web. initialize acc to 0 MOVC A.@A+DPTR . STORE ACC.@A+DPTR MOV R3. inc DPTR to point to expected output MOV PORT.

The coil is mounted on a spinning shaft in the middle of the motor. or current that it draws under no load. depending on the current flow. Motors may draw near the stall current for a brief period of time when starting up. or back voltage. Current Motors draw current depending on the load they're pulling. It's called blowback. and you turn it off. Dropping below rated voltage reduces the motor's power. Usually more load means more current. This stall current is much greater than the running current. and operating above the rated voltage may burn the motor out. and slowest speed at no more than 50% less than the rated voltage. the principle works in reverse as well. All inductive loads (like motors. Plan on the motor's top speed being at rated voltage. So if you've got a motor spinning. Your power supply for a motor should be able to handle the stall current with extra amperage to spare. and we get circular motion. electromagnets. However. the greater the magnetic field. When you spin a wire in an existing magnetic field. Speed Motor speed is given in revolutions per minute (RPM's). use it to attract or repulse a magnetic body. to stop the back voltage. and therefore the greater the attraction or repulsion. .will be either attracted to one magnet and repelled by the other. The higher the current. This current comes back in the reverse direction of the current flow you generated to run the motor. the fact that the motor's coil is spinning in a magnetic field will generate a current in the wire for a brief amount of time. the field induces a current in the wire. which is the current it draws when it's stopped by an opposing force. Every motor has a stall current. Usually it's stopped by putting a diode in line with your motor. and it can cause damage to your electronics. and solenoids) work on this same principle: induce a magnetic field by putting current through a wire. Motor Characteristics There are a few characteristics common to all motors that you should keep in mind when looking for motors: Voltage The rated voltage of a motor is the voltage at which it operates at peak efficiency. but it's best to plan to operate them at their rated voltage. it spins from one to the other. As the coil is alternately attracted to one magnet and repulsed by the other. to overcome their inertia. or vice versa. Most DC motors can be operated somewhat above or below their range.

.-lb. It works on exactly the principle discussed above. When the motor turns. and the pot is turned by the turning of the motor. g-cm (gram-centimeter).. the motor spins in one direction. oz. There are two terminals. Resistance Often you'll see a motor rated in ohms. the motor spins in the opposite direction. By varying the current supplied to the motor. and the motor can pull one pound on that shaft. The DC Motor The DC Motor is the simplest of the motors discussed here. DC motors are usually very fast.-in. By switching the polarity of the terminals. it changes . It's measured by the force a motor can pull when the opposing force is attached to a shaft attached to its center rod. The Servo Motor Servo motors are a variation on the gearhead motor coupled with a potentiometer to give feedback on the motor's position. you can calculate the motor's current draw if you know the rated voltage and the coil resistance. but you do need power. This just gives you the resistance that the motor's coil offers. and any other weight to length variation you can think of.Torque Torque is the measure of a motor's pulling force. If the shaft sticks out a foot from the motor's center. They are useful when you don't need a lot of speed. Specific techniques for doing these tasks are discussed below. you vary the speed of the motor. and when you apply direct current to one terminal and ground the other. The gears of the gearbox on a servo are attached to a potentiometer inside the case.. When you apply current to the other terminal and ground the first terminal. so sometimes you will see it as ft. The pot is connected to a capacitor in a resistor-capacitor circuit (R-C). Motor manufacturers haven't standardized this measurement. in. you give the motor power to turn. and by pulsing this R-C circuit.. They have a box on the top of the motors containing a series of gears that slow the rotational speed of the motor down and increase the torque. the motor's torque is one foot-pound. spinning at several thousand revolutions per minute (RPM). lb-ft. you reverse the direction of the motor. The Gearhead Motor Gearhead motors are a subset of DC motors. Using Ohm's Law (voltage = current x resistance).oz.

A pulse of 1 ms will turn the motor to 0 degrees. . 2 ms will turn it to 180 degrees. This third line is used to set the position of a servo. The center shaft has a series of magnets mounted on it. unlike DC motors. Servos have three wires to them. The first thing to do is to understand the wiring for a stepper motor.). you set the motor's position in a range from 0 to 180 degrees. Furthermore. and other devices where precise positioning of the motor is necessary. By pulsing the R-C circuit. They rotate 0 to 180 degrees depending on the pulsewidth. They can be very useful for moving a precise distance. which in turn feeds the motor again. with six wires and four coils (actually two coils divided by center wires on each coil). and the coils surrounding the shaft are alternately given current or not. stepper motors have very high torque when stopped. The Stepper Motor Stepper motors are different than regular DC motors in that they don't turn continuously. This design allows for very precise control of the motor: by proper pulsing. To do this. two-degree increments. creating magnetic fields which repulse or attract the magnets on the shaft. The most common type is a unipolar stepper motor. it can be turned in very accurate steps of set degree increments (for example. which have two. but move in a series of steps. Unlike other DC motors. etc.the resistance of the R-C circuit. The first two in a servo are power and ground. the kind most often used in small physical computing projects. steppers often provide more torque at lower speeds. disk drives. usually take a pulse of between 1-2 ms every 18-20 ms. Hobby servos. so once you've moved the motor to a new position. They are used in printers. Steppers usually move much slower than DC motors. half-degree increments. To control a stepper. and the third is a digital control line. since there is an upper limit to how fast you can step them (5-600 pulses per second. you do not have to reverse the polarity of a servo's power connections to reverse its direction. it's necessary to create a stepper driver that will energize the coils in the right order to make the motor move forward. take an ohmmeter to the wires and measure the resistance from one wire to another. A stepper motor is a motor controlled by a series of electromagnetic coils. unlike most DC and gearhead motors. The outer wires for each coil will have a definite resistance that is double the resistance between the inner wire and . A servo needs to see a pulse every 18-20 ms even when it is not turning. it's essential to keep pulsing it with the same pulsewidth to keep it there. to keep it in its current position. causing the motor to rotate. since the motor windings are holding the motor in place like a brake. typically. However.

as follows: . get a variable DC power supply. which should read as an error on your meter.g. When you put voltage across two wires of a coil (e. so you'll need a separate power supply for it. or 2 to 4). so don't go too far. It is possible to damage a motor this way.either of the two outer wires.g. Ideally you'll know the voltage from the manufacturer.: if the resistance between wires 1 and 2 is x Ohms. 1 and 4. then that between 1 and 3 is 2x Ohms. Remember. you would drive the stepper by connecting the 4 phase wires to a good power transistor or MOSFET. Like other motors. apply the minimum voltage (hopefully 1V or so). 12V.g. apply voltage across two wires of a coil (e. 24V. Typically.g. but if not. two wires that are not connected (e. 5. 1 to 3. that's bad for the motor). 1 to 3 or 4 to 6) and slowly raise the voltage until the motor is difficult to turn. the stepper requires more power than a microcontroller can give it. 9V. Typical voltages for a stepper might be 5V.and the 2 common wires to the supply voltage. or 6) have infinite resistance. as follows in the diagram below: e. you should find that the motor is very difficult to turn (don't force it.

So for examples. see this example. stepping in the other direction is simply a matter of doing the steps in reverse order. Knowing the position is a matter of knowing how many degrees per step. and it's turned 180 steps. For more on stepper control. the transistors are TIP120 Darlington transistors. How Stepper Motor Works? . or 360 degrees. Once you have the motor stepping in one direction. if you have a 2-degree stepper. A convenient way to do this is with a ULN2003 or ULN2004 Darlington transistor array from Allegro Micro.In this diagram. or one full revolution. and counting the steps and multiplying by that many degrees. then it's turned 2 x 180 degrees.

and which don't move. b2 (brown) should be connected to a driver (ULN2003) as s .Stepper motors are very different from a regular DC motors. Stepper Motor Connections Unipolar motor should have five or six connections depending on the model.the permanent magnet that rotates inside. If the motor has six c pictured above. Instead of spinning like DC motors do. b1 (black).four c west) that are part of the case. and stator . Rotor can be moved by sequentially applying one or two coils at a time. s specific resolution for each pulse. you have to join pins 1 and 2 (red) together and connect them to a (+) 12-24V voltag pins. The motor that we are using needs 48 steps / pulses just to comp That should be enough to tell about Another advantage of stepper motors is the fact that their speed of rotation can be achieved almo change the spinning Stepper motor consists of a rotor . a1 (yellow). a2 (orange).

Pulse 1 2 3 4 ON Coil a1 ON Coil b1 ON ON ON ON ON ON Coil a2 Coil b2 3. Each p approximately 3.75 degrees.5 degrees.the simplest mode turns one coil ON at a time. 48 pulses are needed to comp Each pulse moves rotor by 7. Pulse 1 2 3 4 Coil a1 ON ON ON ON Coil b1 Coil a2 Coil b2 2.Stepping Modes There are several stepping modes that you can use to drive the stepper motor. Half Stepping . The following sequence has to be r for motor to complete one revolution. Pulse 1 2 3 4 5 6 7 8 ON Coil a1 ON ON ON ON ON ON ON ON ON ON ON Coil b1 Coil a2 Coil b2 Stepper Motor Driver In able to move the rotor you will need a driver. High Torque Stepping . Single Stepping . Notice the mix of single stepping mode (lighter green) and high torque green). 1.high power / precision mode turns ON two coils on at a time. Each pulse moves rotor by 7. The following sequence has to be repeated 12 times for mot revolution.stepping is doubled and motor needs 96 pulses to complete one revolution. Driver is a circuit that applies a . 48 pulses complete one revolution.5 degrees.

Direction Control To control a DC motor from a microcontroller.voltage to any of the four stator coils. Controlling Stepper Motor with a Port pins: Controlling DC Motors There are two easily controllable parameters of a DC motor. direction and speed. the polarity of the motor is reversed. Driver can be built with IC such as ULN2003 (pictured on the circuit diagram). It looks like this: . To control the speed. To control the direction. or four darlington transistors or four power transistors such as 2N3055. the input voltage is varied using pulsewidth modulation. you use switching arrangement known as an H bridge.

voltage flows from the supply to 1 to the motor to 4 to ground. in pairs. to simulate a voltage. when one is high. A premanufactured H-bridge chip will include diodes to protect the transistors from back voltage. Although you can make your own H-bridges. sometimes a current sensing pin to sense the current the motor is drawing. If you were using this circuit. When 2 and 3 are closed and 1 and 4 are open. the motor won't get enough power to turn. usually 50% of the rated voltage. There are many motor drivers available from various electronics suppliers. so that the proper two transistors always switch together. so that a microcontroller can switch the motor. Here are some examples of puleswidths and the voltages they would simulate: . it's usually easier to use a controller manufactured specifically for the job. but within a certain range. you'd want to make sure that control pins 1 and 2 were always reversed. If the voltage drops too far. Look around to find one that suits your needs and price range.When switches 1 and 4 are closed and 2 and 3 are open. and much more. Speed A DC motor's speed is proportional to the supplied voltage. An H-bridge can be built from transistors. This means that you pulse the motor on and off at varying rates. polarity is reversed. the other is low. the motor will run at varying speeds. like this: You can see that there are six transistors here. and voltage flows from the supply to 3 to the motor to 2 to ground. The most effective way to adjust the speed is by using pulsewidth modulation. the outer two are used to switch the inner four.

When the duty cycle is reduced to one quarter of the total time. we're far more used to thinking and dealing with decimal numbers. Individual LEDs can of course display the binary states of a set of latches or flip-flops. an expanded version of this is used in many ways. there are many controllers that will vary the speed of your motor. the effective voltage is about half the total voltage. if all we want to display is numbers. A much . the effective voltage is about one quarter of the total voltage. However. To this end. so if you don't want to delve into the timing issues yourself. you can rely on products made for the job. One possibility is a matrix of 28 LEDs in a 7×4 array. this becomes a bit expensive. However. Indeed.When the time that the voltage is high (the duty cycle) is half the total time in question. We can then light up selected LEDs in the pattern required for whatever character we want. SEVEN SEGMENT DISPLAYS Introduction One common requirement for many different digital devices is a visual numeric display. As with direction. for fancy displays. we want a display of some kind that can clearly represent decimal numbers without any requirement of translating binary to decimal or any other format.

so that the two decimal points look like a colon between the two digits. Most seven-segment digits also include a decimal point ("dp"). . We've all seen seven-segment displays in a wide range of applications. and many household appliances already have such displays. This requires just seven LEDs (plus an eighth one for the decimal point. The technique is commonly used in LED clock displays. for example. to distribute the light from the LED evenly over a fixed bar shape. This improves readability of large numbers on a calculator. The result is known as a seven-segment LED. or have a decimal point on each side. Segment "g" is the center bar. Seven-Segment Display Layout The illustration to the right shows the basic layout of the segments in a seven-segment display. digital instruments. In this experiment. we'll look at what they are and how they can display any of the ten decimal digits 0-9 on demand. most displays are actually slanted a bit.better way is to arrange the minimum possible number of LEDs in such a way as to represent only numbers in a simple fashion. In addition. Clocks. The segments themselves are identified with lower-case letters "a" through "g. The decimal point is shown here on the right. making them look as if they were in italics." with segment "a" at the top and then counting clockwise. if that is needed). and some also include an extra triangle to turn the decimal point into a comma. watches. but some display units put it on the left. A common technique is to use a shaped piece of translucent plastic to operate as a specialized optical fiber. This arrangement allows us to turn one digit upside down and place it next to another. The seven bars are laid out as a squared-off figure "8".

Seven-segment displays can be packaged in a number of ways. However. The three most common methods are fluorescent displays (used in many line-powered devices such as microwave ovens and some clocks and clock radios). One limitation of the DIP package is that it cannot support larger digits. so a clear plastic bubble is molded over each digit to act as a magnifying lens. liquid crystal displays (used in many batterypowered devices such as watches and many digital instruments). To get larger displays for easy reading at a distance. The sides of the end bubbles are flattened so that additional packages of this type can be placed endto-end to create a display of as many digits as may be needed. and LEDs (used in either line-powered or battery-powered devices). the decimal point is on the left. fluorescent displays require a fairly high driving voltage to operate. and thus can display a digit that is significantly larger than will fit on a standard DIP footprint. Three typical packages are shown above. The second package is essentially a 14-pin DIP designed to be installed vertically. we will work with a seven-segment LED display in this experiment. Even larger displays are also available. Note that for this particular device. Seven-segment displays can be constructed using any of a number of different technologies. The package on the right above is larger than the other two. Therefore. some digital clocks sport digits that are two to five inches tall. it is necessary to change the package size and shape. On the left we see three small digits in a single 12pin DIP package. The individual digits are very small. and liquid crystal displays require special treatment that we are not yet ready to discuss. This is not true of all seven-segment displays in this type of package. Schematic Diagram .

the LEDs in a sevensegment display are not isolated from each other. or all of the anodes. (In some cases. In other cases. This means fewer electrical connections to the package. Rather. or vice-versa. are connected together into a common lead. the common connections are made to groups of LEDs. we will use a common-cathode display for our experimental example. and logic families. and also allows us to easily enable or disable a particular digit by controlling the common lead. and the external wiring must make the final connections between them. either all of the cathodes. you simply need to take the specific connection details into account.) There is no automatic advantage of the common-cathode seven-segment unit over the common-anode version. INTERFACING A/D CONVERTERS TO 8051 . When laying out circuits using such devices.As shown in the two schematic diagrams above. Each type lends itself to certain applications. the common connection is made available at more than one location for convenience in laying out printed circuit boards. while the other end of each LED is individually available. configurations.

we make CS = 0 and send a high to low pulse to the RD pin to get the data out of the ADC804 chip. Conversion time is defined as the time it takes the ADC to convert the analog input to a digital number. conversion is the another factor in judging an ADC. and many other natural quantities. The ADC converts the analog input to its binary equivalent and holds it an internal register. The ADC804 IC is an analog to digital converter in the family of the ADC80 series from National Semiconductors. but in the physical world everything is analog. the ADC804 starts converting the analog input value of Vin to an 8 bit digital number. It is a normally high pin when the conversion is finished. CHIP SELECT (CS): Chip select is an active low input used to activate the ADC804 chip. Transducers are also referred to as sensors. Digital computers use binary values. pressure. . but it can’t be faster than 110usec. INTERRUPT (INTR): This is an active low output pin which indicates the end of conversion. Therefore. the conversion time varies depending on the clocking sign als applied to the CLK R and CLK IN pins. humidity. In the ADC804. light. It works with +5v and has a resolution of 8bits. The RD is referred to as output enable. this pin must be low. velocity. A physical quantity is converted to electrical signals using a device called transducers. RD is used to get the converted data out of the ADC804 chip. When CS=0. the INTR pin is forced low by the ADC804. if a high to low pulse is applied to the RD pin. it goes low to signal the MCU that the converted data is ready to be picked up. To access the ADC804. It is also available from many other manufactures. and velocity are a few examples of physical quantities that we deal everyday. READ (RD): This is an input signal and is active low. When the conversion is completed . Although there are sensors for temperatures. If CS = 0 when WR makes a low to high transition. pressure. we need an analog to digital converter to translate the analog signals to digital numbers so that the microcontrollers can read them. After INTR goes low. the 8 bit digital output shows up at the D0-D7 data pins. The amount of time it takes to convert varies depending on the CLK IN and CLK R values. Temperature. WRITE (WR): This is an active low input used to inform the ADC804 to start conversion process. In addition to resolution. they produce an output that is voltage.ADC devices Analog to digital converters are among the most widely used devices for data acquisition.

which is for an 8 bit ADC. Often the Vin(-) pin is connected to ground and the Vin(+) pin is used as the analog input to be inverted to digital. Keep polling until it goes low. If this pin pin is open( not connected ). For example. Vref/2 is an input voltage used for the reference voltage. However . Vin is the analog input voltage and step size is the smallest change. After the INTR is low. These are tri state buffered and the converted data is accessed only when CS = 0 and RD is forced to low. Still. Vin = Vin(+) – Vin(-). To calculate the output voltage. whether we want it or not. the 804 has an internal clock generator. The clock frequency is determined by the equation f = 1/ 1. If it goes low the conversion is completed and we an go to the next step.1RC Vin(+) and Vin(-): These are the differential analog inputs where. reality is different. 2. the analog input voltage for the AD804 is in the range of 0 to 5v. Keep monitoring the INTR is high. Sequence of steps: 1. That is probably one of the reasons why numerical systems which differ from a decimal are still hard to understand. 3. the CLK IN and CLK R pins are connected to a capacitor and a resistor as shown in the figure. Decimal numerical system that people use in everyday life is so far behind . use the formula Dout = Vin / step size Where Dout is digital data output. It is also used as a reference voltage when the Vrer/2 input is open. VCC and Vref: This is the +5v power supply. Vref/2 is connected to 2 volts. However.CLK IN and CLK R: CLK IN is an input pin connected to an external clock source when an external clock is used for timing. To use the internal clock generator of the ADC804. if the analog input range needs to be 0 to 4 volts. Numerical Systems Introduction It was always difficult for people to accept the fact that some things differ from them or their way of thinking. Make CS = 0 and send a low to high pulse to pin WR to start conversion. there are many applications where the analog input applied to Vin needs to be other than the 0 to 5V. D0 – D7: D0 – D7 are the digital data output pins. we make CS = 0 and send a high to low pulse to the RD pin to the data out of the ADC804 IC chip.

The sum of values of each decimal gives the value of the whole number. Binary numerical system is used in computers and microcontrollers because it is far more suitable for processing than a decimal system. in order to compare it with the other two. 5. subtraction. 4. 2. etc. Binary and hexadecimal numerical systems are especially interesting for the subject of this book.1 Decimal numerical system Decimal numerical system is defined by its basis 10 and decimal space that is counted from right to left. we will also discuss a decimal system. so we won't discuss it further. binary number consists of binary digits 8. B.2 Binary numerical system Binary numerical system differs in many aspects from the decimal system we are used to in our everyday lives. and that we need to tell someone to . 9.1. 16 or 32. and multiplication in a decimal numerical system are used in a way that is already known to us. The value of each decimal is determined by its position in relation to the whole number represented in the given numerical system.the binary system used by millions of computers around the world. and with a hexadecimal system 16. that basis is 10. and consists of numbers 0. next by 100. 7. Its numerical basis is 2. B. '1' or '0'. Beside these. Example: 10011011 binary number with 8 digits In order to understand the logic of binary numbers. Each numerical system are based on some basis. we will consider an example. division. That means that the end right digit of the total sum is multiplied by 1. 3. we will discuss it here because of its relatedness to other numerical systems. Usually. and it is not important in view of the contents of our book to discuss why. and each number can have only two values. With a decimal numerical system. It will be enough for now to adopt this information. with binary 2. Even though a decimal numerical system is a subject we are well acquainted with. next one by 10. Let's say that we have a small chest with four drawers. Example: Operations of addition. 8. 6.

Depending on the position in a binary number. Example: As you can see. In other words. B=1 represents the left column. and for A=0. digits carry different values which are multiplied by themselves. 4 in the second drawer. or how to get a numerical value from a series of zeros and ones in a way we can understand. and B=0. it refers to the upper row of drawers. right. 10 and 11". Now it is already easier to explain from which drawer we need something. Let's further suppose that there are few marbles in each of the drawers: 2 in the first one. etc. the right (next picture). of course.01. What remains is for us to get acquainted with logic that is used with binary numerical system. converting a binary number into a decimal number is done by calculating the expression on the left side. references like "first. second. 01. above. and the desired drawer is clearly defined. then we would have a problem. However. bottom (drawer). This procedure is called conversion from a binary to a decimal number. Nothing is more simple.. There are many solution to this problem. We simply need to state one of the four combinations: 00. or conversion of common numbers from a decimal into binary form.bring something from one of the drawers to us. and types with B. we will say left side. If A=1. bottom row. 10 or 11. if we had to do this without the use of instructions like left. and by adding them we get a decimal number we can understand. This characteristic naming of each drawer individually is nothing but binary numerical representation. beneath. Similarly with columns. third and fourth" are exchanged with "00. but we should look for one that is most beneficent and practical! Lets designate rows with A. 7 in the third and 3 in the .

one of which is expanding the number of binary digits in the sum as . and that for all values above that we must add new binary digits. in binary representation it will be a zero. their sum remains zero. the biggest number that can be represented by a binary digit is the one obtained when basis 2 is graded onto a number of binary digits in a binary number and thus obtained number is decremented by one." It should be noted that both question and the answer are very clear even though we did not use the standard terms. Example: We can check whether result is correct by transferring these number to decimal numerical system and by performing addition in it. similar to the decimal numerical system. Under these conditions. for numbers from 0 to 15. or 16 different values. For reasons of clarity and legibility. including numbers '0' and '15'. Trouble comes when sum is greater than what can be represented by a binary number with a given number of binary digits. four. we will review addition and subtraction only in this chapter. Let's also say to the one who's opening the drawers to use binary representation in answer. result is '1'. and the answer would be: "There are 100 marbles in 01. Operations which exist in decimal numerical system also exist in a binary system.fourth drawer. for numbers from 0 to 7 it is enough to have three digits. but with transferring '1' to a higher position that is added to digits from that position. Example: This means that it is possible to represent decimal numbers from 0 to 15 with 4 binary digits. value 9 as the second. question would be as follows: "How many marbles are there in 01?". If both digits being added are zero. and value 19 as the sum. Thus we have proven that operation was done correctly. Simply said. It should further be noted that for decimal numbers from 0 to 3 it is enough to have two binary digits. The sum of two ones gives two. Different solutions can be applied then. etc. Basic rules that apply to binary addition are: Addition is done so that digits in the same numerical positions are added. With a transfer we get a value 10 as the first number. and if they are '0' and '1'. So.

in

the

previous

example.

Subtraction, like addition is done on the same principle. The result of subtraction between two zeros, or two ones remains a zero. When subtracting one from zero, we have to borrow one from binary digit which has a higher value in the binary number. Example:

By checking the result as we did with addition, when we translate these binary numbers we get decimal numbers 10 and 9. Their difference corresponds to number 1 which is what we get in subtraction. B.3 Hexadecimal numerical system Hexadecimal numerical system has a number 16 as its basis. Since the basis of a numerical system is 16, there are 16 different digits that can be found in a hexadecimal number. Those digits are "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F". Letters A, B, C, D, E and F are nothing but values 10, 11, 12, 13, 14 and 15. They are introduced as a replacement to make writing easier. As with a binary system, here too, we can determine with same formula what is the biggest decimal number we can represent with a specific number of hexadecimal digits. Example: With two hexadecimal digits

Usually, hexadecimal number is written with a prefix "$" or "0x" ,or suffix"h" , to emphasize the numerical system. Thus, number A37E would be written more correctly as $A37E, 0xA37E, or A37Eh. In order to translate a hexadecimal number into a binary numerical system it is not necessary to perform any calculation but simple exchange of hexadecimal digits with binary digits. Since the maximum value of a hexadecimal number is 15, that means that it is enough to use 4 binary digits for one hexadecimal digit.

Example:

By checking, that is transferring both numbers into decimal numerical system, we get a number 228 which proves the accuracy of our action. In order to get a decimal equivalent of a hexadecimal number, we need to multiply each digit of a number with number 16 which is gradated by the position of that digit in hexadecimal number. Example:

Addition is, like in two preceding examples, performed in a similar manner. Example:

We need to add corresponding number digits. If their sum is equal 16, write 0 and transfer one to the next higher place. If their sum is greater than 16, write value above and transfer 1 to the next higher digit.Eg. if sum is 19 (19=16+3) write 3 and transfer 1 to the next higher place. By checking, we get 14891 as the first number, and second is 43457. Their sum is 58348, which is a number $E3EC when it is transferred into a decimal numerical system. Subtraction is an identical process to those in previous two numerical systems. If the number we are subtracting is smaller, we borrow from the next place of higher value. Example:

By checking this result, we get values 11590 for the first number and 5970 for the second, where their difference is 5620, which corresponds to a number $15F4 after a transfer into a decimal numerical system. Conclusion

Binary numerical system is still the one that is most in use, decimal the one that's easiest to understand, and a hexadecimal is somewhere between those two systems. It's easy conversion to a binary numerical system and easy memorization make it, along with binary and decimal systems, one of the most important numerical systems.

Glossary
Microcontroller A processing unit with peripherals in one chip. I/Opin External microcontroller's connector pin which can be configured as input or output. In most cases I/O pin enables a microcontroller to communicate, control or read information. Software Information that microcontroller needs in order to be able to function. Software can not have any errors if we want the program and a device to function properly. Software can be written in different languages such as: Basic, C, pascal or assembler. Physically, that is a file on computer disc. Hardware Microcontroller, memory, supply, signal circuits and all components connected with microcontroller.The other way of viewing this (especially if it's not working) is, that, hardware is something you can kick. Simulator Software package for PC which simulates the internal function of microcontroller. It is ideal for checking software routines and all the parts of the code which do not have over demanding connections with an outside world. Options are installed to watch the code, movement around the program back and forth step by step, and debugging. ICE ICE (In Circuit Emulator), internal emulator, very useful part of the equipment which connects a PC instead of microcontroller on a device that is being developed. It enables software to function on the PC computer, but to appear as if a real microcontroller exists in the device. ICE enables you to

By using it we avoid constant erasing and writing of EPROM memory. It contains a section for discovering errors. to see what is going on in the microcontroller and how it communicates with an outside world. but it only emulates its memory. and has a form "understood" by microcontrollers. which error we are not aware of. Errors can be quite simple such as typing errors.EEPROM. List-file This is a file made by assembler translator and it contains all instructions from source file with addresses and comments programmer has written.FLASH. It is mostly used in microcontrollers that have external memory.HEX where the name HEX file comes from. Source-File File written in the language understood by man and assembler translator. Other errors will need to be searched for by trying it out and watching how device functions. By translating the source file.move through program in real time. HEX-file This is a file made by assembler translator when translating a source file. Debugging Error made in writing a program. we get HEX and LIST files. A continuation of the file is usually Filename . ROM. First one can not be . Assembler Software package which translates source code into a code which microcontroller can understand.RAM Types of memories we meet with microcontroller use. and quite complex such as incorrect use of program language. Assembler will find most of these errors and report them to '. EPROM-emulator EPROM Emulator is a device which does not emulate the entire microcontroller like ICE emulator. This part is used when we debug a program from errors made when program was written. This is a very useful file for keeping track of errors in the program.LST' file.EPROM. File extension is LST which is where its name comes from.

Program activates its response if necessary. but unlike EEPROM memory it does not have such a great number of cycles of writing and erasing at memory locations. and can not be erased. and mega byte has 1024 kilobytes. Flag Bits from a status register. The second is erasable with UV lamp. Byte. Programmer Device which makes it possible to write software in microcontroller memory. and it has 8 bits. Microcontroller takes from this location information about a section of the program that is to be executed as an answer to some event of interest to programmer and device. The basic unit is a byte. what you write in it once. Kilobyte. Kilobyte has 1024 bytes.erased. thus enabling the microcontroller to work independently. Fourth one is electrically erasable. using voltage which microcontroller operates on. but it does not hold back the contents as the previous when there is supply shortage. or section of a file which contains program instructions. Interrupt vector or interrupts Location in microcontroller memory. Carry Transfer bit connected with arithmetic operations Code File. Addressing Determines and designates certain memory locations. Third one can be erased electrically. ASCII Short for "American Standard Code for Information Interchange". By their activation. but it serves for different variables and inter-results. Megabyte Terms designating amounts of information. program is not stored in it. Fifth one is fast. It consists of the hardware section usually connected with one of the ports and . Thus. programmer is informed about certain actions. stays forever. It is widely accepted type of coding where each number and letter have their eight-bit code.

The two separate fetches slows up the controller's operation. As an instruction is being "pre-fetched". it first fetches an instruction. Among some of the typical features of a RISC processor: . and others might only recognize certain addressing modes. allowing the programmer to use one instruction in place of many simpler instructions. The typical CISC microcontroller has well over 80 instructions. The benefits of RISC design simplicity are a smaller chip. Von-Neumann Architecture Microcontrollers based on the Von-Neumann architecture have a single "data" bus that is used to fetch both instructions and data. Harvard Architecture Microcontrollers based on the Harvard Architecture have separate data bus and an instruction bus. By implementing fewer instructions. CISC Almost all of today's microcontrollers are based on the CISC Complex Instruction Set Computer) concept.software section used on the computer as a program. The advantage of the CISC architecture is that many of the instructions are macrolike. the next instruction is ready to go. RISC The industry trend for microprocessor design is for Reduced Instruction Set Computers (RISC) designs.Harvard architecture (separate buses for instructions and data) allows simultaneous access of program and data. When such a controller addresses main memory. and very low power consumption. smaller pin count. and overlapping of some operations for increased processing performance . Once the current instruction is complete. the current instruction is executing on the data bus. but there is some added silicon complexity. This is beginning to spill over into the microcontroller market. Some might only operate on certain address spaces or registers. It is quite common for the instructions to all behave quite differently. and then it fetches the data to support the instruction. This pre-fetch theoretically allows for much faster execution than Von-Neumann architecture. This allows execution to occur in parallel. the chip designed is able to dedicate some of the precious silicon real-estate for performance enhancing features. Program instructions and data are stored in a common main memory. many of them very powerful and very specialized for specific control tasks.

if you write a slow. A [usually] expensive piece of hardware that even for the cheaper versions will run you at least $700. while at the same time capturing information. An assembly/machine language program is fast and small. be too big. large. A simulator can't support real interrupts or devices.just MUCH slower. and usually runs much slower than the real device the program is intended for. and be stupid. Of course. The emulator can either be a stand alone device with its own display. An emulator is a sophisticated device that pretends that it is the microprocessor itself. Eliminates the erase/burn/program EPROM cycle common in microcontroller program development. It is not easy for humans to read and is a common cause of migraine headaches. The interpreter itself is a program that sits resident in the microcontroller. that's right. Emulators If you've got the money. It executes a program by reading each language statement one at a time and then doing what the .. Machine and Assembly languages Machine language is the program representation as the microcontroller understands it i. You can work out ideas or learn about microcontrollers by experimenting with small code fragments and watching on the screen what happens.e. Each assembly language statement corresponds to one machine language statement (assembly language contains mnemonics). then it will run slowly. This is because you are in complete charge of what goes into the program.Instruction pipelining increases execution speed . Interpreters An interpreter is a high level language translator that is closer to natural language. This is a piece of equipment that plugs into your target. Some manufacturers have a cross between a software simulator and the hardware emulator .Orthogonal (symmetrical) instruction set for programming simplicity. instructions have no special combinations. and the pins will toggle and react like they should .a hardware simulator. It provides full and total control over your target. or side effects Simulators A simulator runs your microcontroller program on a host machine (such as your PC). or it can be interface to a PC. stupid program. exceptions. Assembly language is a human-readable form of machine language which makes it much easier for us. restrictions. while at the same time not requiring any resources from the target. Contents of registers or variables can be altered to change the way the program runs. a preposition at the end of a sentence!). You can step through the code to see exactly what is happening as the program runs. this is the equipment you want to develop your system with (yeah. it is in form of 0s and 1s. allows each instruction to operate on any register or use any addressing mode.

The machine language program is then burned onto an EPROM or downloaded directly to the microcontroller. The designer can first train a software neural network to produce the desired output from a given set of inputs and outputs and then use a software tool to extract the underlying rules from the neural network. This is accomplished by translating the program (on a host machine such as a desktop PC) directly into machine language. a fuzzy-logic system can be precisely described. In contrast. The inputs must represent the behavior of the system that is being programmed. If the network's output does not agree with the desired result. from conception to implementation. The two methods are very different from each other. However. its desired logical operation must be analyzed and translated into fuzzy-logic rules. or something close to it. and the outputs should match the desired result within some margin of error. and derivate) control techniques. The advantage of neural networks is that it is possible to design them without completely understanding the underlying logical rules by which they operate. Fuzzy Logic and Neural Networks Fuzzy Logic and neural networks are two design methods that are coming into favor in embedded systems. This is the step where neural networks technology can be helpful to the fuzzy-logic designer. Fuzzy logic is not a complete design solution. when it is presented with new and unknown data. the advantages and disadvantages of the two can complement each other. It works best when it is applied to non-linear systems with many inputs that cannot be easily expressed in either mathematical equations used for PID control or IF-THEN statements used for event control. It supplements rather than replaces traditional event control and PID (proportional. Fuzzy logic relies on grade of membership and artificial intelligence techniques. also has some popular support due to that company's extensive use of that language. PL/M. The two most popular interpreters for microcontrollers are BASIC and FORTH. The extracted rules are translated into fuzzy-logic rules. integral. from Intel. The microcontroller then executes the translated program directly. Before a fuzzy control system is designed. Compilers A compiler is a high level language translator that combines the programming ease of an interpreter with greater speed. The most popular microcontroller compilers are C and BASIC. without having to interpret first. The neural network designer applies a set of inputs to the network and "trains" it to produce the required output. After training it is assumed that the network will also produce the desired output. . the structure of the neural network is altered until it does.statement says to do.

while other generates C code which can be compiled for any microcontroller. most manufacturers of microcontrollers have introduced fuzzy logic software.In an effort to change fuzzy logic from a "buzzword" (as it is in most parts of the world) to a well established design method (as it is in Japan). Most software generates code for specific microcontrollers. .

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.