Top Banner

of 46

Embedded System Microcontroller

Apr 03, 2018

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 7/29/2019 Embedded System Microcontroller

    1/46

    1 EMBEDDED SYSTEM

    Embedded System is a combination of hardware and software used to

    achieve a single task. It is a computer system that monitor respond to, or

    control an external environment. Environment are connected to systems

    through sensors, actuators and other I/O interfaces. Embedded system must

    meet timing and other constraints imposed on it by environment

    An Embedded system is a component within some larger system. It is

    contrast with general-purpose computers. The software in the embedded

    system is called firmware. An Embedded system is an intelligent firmware

    designed for a definite process to be achieved perfectly. An Embedded

    system in general incorporates hardware, operating system, peripheral

    devices and communication software to enable to perform the predefined

    functions.

    CHARACTERISTICS OF EMBEDDED SYSTEM

    In-built Intelligence.

    Immediate control of hardware.

    Uses dedicated software.

    Performs a specific function.

    Processing power and Memory limitations.

    Respond to external events.

    Timeliness, Robustness/Safety.

    CLASSIFICATION OF EMBEDDED SYSTEM:

  • 7/29/2019 Embedded System Microcontroller

    2/46

    REAL TIME SYSTEMS:

    RTS is one, which has to respond to events within a specified dead-

    line. A right answer after the dead line is a wrong answer. RTS are some-

    times classified

    into three categories:

    Hard Real Time System.

    Soft Real Time System.

    Firm Real Time System.

    HARD REAL TIME SYSTEMS:

    "Hard" real-time systems have very narrow response time

    The correctness of response includes a description of timeliness

    Deadlines are specified as points in time that occur as a fixed time

    interval following an event.

    Example: Nuclear power system, Cardiac pacemaker.

    SOFT REAL TIME SYSTEM:

    "Soft" real-time systems have reduced constrains on "lateness" but

    still must operate very quickly and repeatable.

    Soft timeliness requirements are specified as time constraints that may

    be violated to some degree, without affecting the correctness of the

    systems behavior.

    Example: Railway reservation system extra seconds the data

    remains valid.

  • 7/29/2019 Embedded System Microcontroller

    3/46

    If a single computation is late, it is not usually significant, although

    consistently late computation can result in system failure.

    Throughput may be specified as an average response time or

    bandwidth or as a bounded mean lateness.

    FIRM REAL TIME SYSTEM:

    Firm deadlines are a combination of both hard and soft timeliness

    requirements.

    The computation has a short storage soft requirement and a longer

    hard requirement.

    A patient ventilator must mechanically ventilate the patient, a certain

    amount in the longer run.

    A breath could come a few seconds late without affecting patient a

    certain amount in the long run.

    3.3 MICROCONTROLLER

    A microcontroller (also MCU or C) is a functional computersystem-

    on-a-chip. It contains a processor core, memory, and programmable

    input/output peripherals. Microcontrollers include an integrated CPU,

    memory (a small amount of RAM, program memory, or both) and

    peripherals capable of input and output. Microcontrollers are used in

    automatically controlled products and devices.

    http://en.wikipedia.org/wiki/Computerhttp://en.wikipedia.org/wiki/Integrated_circuithttp://en.wikipedia.org/wiki/Input/outputhttp://en.wikipedia.org/wiki/Computerhttp://en.wikipedia.org/wiki/Integrated_circuithttp://en.wikipedia.org/wiki/Input/output
  • 7/29/2019 Embedded System Microcontroller

    4/46

    BASICS:

    A designer will use a Microcontroller to

    Gather input from various sensors

    Process this input into a set of actions

    Use the output mechanisms on the Microcontroller to do

    something useful.

    MEMORY TYPES:

    RAM:

    Random access memory.

    Ram is a volatile (change) memory.

    It general purpose memory that can store data or programs.

    Ex: hard disk, USB device.

    ROM:

    Read only memory.

    Rom is a non volatile memory.

    This is typically that is programmed at the factory to have certain

    values it cannot be changed.

    Ex: cd...

  • 7/29/2019 Embedded System Microcontroller

    5/46

    3.3.1 ARCHITECTURE OF AT89C51

  • 7/29/2019 Embedded System Microcontroller

    6/46

    8051 Architecture:

    8051 Architecture contains the following:

    CPU

    ALU

  • 7/29/2019 Embedded System Microcontroller

    7/46

    I/O ports

    RAM

    ROM

    2 Timers/Counters

    General Purpose registers Special Function registers

    Crystal Oscillators

    Serial ports

    Interrupts

    PSW

    Program Counter

    Stack pointer

    Pin Description:

  • 7/29/2019 Embedded System Microcontroller

    8/46

    8051 contains 40 pins32 Pins are used for I/O purpose2 Pins for crystal oscillator to produce clock

  • 7/29/2019 Embedded System Microcontroller

    9/46

    2 Pins for Supply and ground1 Pins for reset the controller

    Port 0:Port 0 occupies a total of 8 pins. It can be used for input or

    output. To use the pins of port 0 as both input and output ports.Each pin must be connected externally to 10K ohm pull-upresisters. This is due to the fact that P0 is an open drain.

    Port 1:Port 1 occupies a total of 8 pins. It can be used as input oroutput .In contrast to port 0, this port does not need any pull upresisters since it already has pull up resisters internally. Tomake port 1 an input port, it must be programmed as such bywriting 1 to all its bits.

    Port 2:

    Port 2 occupies a total of 8 pins. It can be used as input oroutput. It already has pull-up resisters internally. To make port2 an input, it must be programmed as such by writing 1 to all its

    bits.

    Port 3:Port 3 occupies a total of 8 pins. It can be used as input oroutput. Port 3 has the additional function of providing someextremely important signals such as interrupts.

    Architecture:

    Two types of architecture are followed.

    I. Van-Neuman Architecture: The width of address and data busis same.

    II. Haward Architecture: The bus width of address and data maynot be same. Pipelinining is possible here.

    Microcontrollers have built-in peripherals, they are,1) Memory

    a. Program memory (Eg. PROM, Flash memory)b. Data Memory (Eg. RAM, EEROM)2. I/O Ports3. ADC

  • 7/29/2019 Embedded System Microcontroller

    10/46

    4. Timers5. USART6. Interrupt controllersPWM/Capture

    MEMORY

    CPU

    I

    N

    T

    E

    R

    R

    U

    P

    T

    I/

    O

    P

    O

    R

    T

    TIMER 1,2

    SPI

    I2C

    UART

    TIMER 0

    ADC

    PARALLEL

    SLAVE

  • 7/29/2019 Embedded System Microcontroller

    11/46

    Peripheral Feature:

    The PIC 16F877A has five serial ports namely A, B, C, D and E. Ithas five parallel ports namely:

    1. PSP (Parallel Slave Port 8 bit wide)2. SSP (Serial Synchronous Port)3. MSP (Master Serial Synchronous Port)4. I^2C (Iter Integrated Circuit)5. SPI (Serial Peripheral Interface)

    256 8 bytes data memory

    8k 14 words program memory

    It has three timerTimer 0 8 bit timer

    Timer 1 16 bit timer

    Timer 2 8 bit timer

    12 bit 10 channelo12 bit accuracy

    oNo external hardware multiplexer is needed

    Sleep mode processor

    No power will be consumed during ideal condition

    Built in temperature sensor

    Built in RAM and EPROM

    RAM is used to control ADC.MSB is stored in RAM when LSB isoutputted.

    PWM: Two captures PWM module. PWM used as DAC. Programmable Low voltage detection Circuitry.

    USART:Universal Synchronous Asynchronous Receiver and Transmitter.

    It converts serial data into parallel and vice versa. For instrumentationstandard MAX 485 data converter should be used.

  • 7/29/2019 Embedded System Microcontroller

    12/46

    This external data converter amplifies the incoming 5V (fromPIC) by four times and gives 20V output i.e. -10V to +10V. Similarly,incoming 20V (from PC) is reduced as 5V by the same MAX 485converter. MAX 485 can be replaced by MAX 232 for computerstandard.

    This is known as Quader-Puller action.

    Key Features

    PIC micro-range

    Reference

    Manual(DS 33023)PIC

    16F873

    PIC16F874 PIC16F876 PIC16F877

    Operating Frequency DC-20MHz

    DC20 MHz DC20 MHz DC20 MHz

    Resets(and Delays) POR,BOR

    (PWRT,OST)

    POR,BOR

    (PWRT,OST)

    POR,BOR

    (PWRT,OST)

    POR,BOR

    (PWRT,OST)

    FLASH ProgramMemory(14-bit words)

    4K 4K 8K 8K

    Data Memory(bytes) 192 192 368 368

    EEPROM DataMemory

    192 192 256 256

    Interrupts 13 14 13 14

    I/O Ports Ports A,B,C PortsA,B,C,D,E

    Ports A,B,C PortsA,B,C,D,E

    Timers 3 3 3 3

    Captures/Compare/PWM modules

    2 2 2 2

    SerialCommunications

    MSSP,USART

    MSSP,USART

    MSSP,USART

    MSSP,USART

    ParallelCommunications

    -- PSP -- PSP

    10-bit Analog-to-Digital Module

    5 inputchannels

    8 inputchannels

    5 inputchannels

    8 inputchannels

    Instruction 35Instructions

    35Instructions

    35Instructions

    35Instructions

  • 7/29/2019 Embedded System Microcontroller

    13/46

    General Features:

    High Performance RISC CPU

    Only 35 instructions are available, hence easy programming ispossible which increase the processing speed.

    Operating speed:

    9600 baud ratePower on Reset

    Whenever the PIC is reset, the program counter reaches the known

    address.

    Watch Dog Timer

    It is used to find Communication Error with its own on chip RCoscillator for reliable operation.

    Low Power Consumption

    High sink/Source Current

    The output of the Embedded Controller can be used to drive printer,relays, solenoid valves etc. No need of driver circuit.

    Compatible to all computer language No need of DLL (Dynamic LinkLibrary)

    Design Features:

    Individual power supply for Analog and Digital circuits is required toavoid drift on analog portion.

    Double regulated filtered reference source is needed to ensure safestADC operation.

    External clock source must be used which enables the user to designthe required speed.

    External CPU Synchronous circuit must be designed incase of PCrequirement.Switch is used to synchronize the Embedded Controller with thePC to get COMOK signal.

  • 7/29/2019 Embedded System Microcontroller

    14/46

    External RS-232 should be used for data conversion.

    Memory Organization:

    There are two memory blocks in PIC microcontroller. Each block hasits own bus so that concurrent access can occur.

    1. Program memory2. Data memory

    Program memory Organization:

    PIC 87 has a 13 bit program counter capable of addressing 8k 14program memory space. Each device has 4k 14 words of program space.

    The reset vector is at 000H

    Receiving Interrupt vector is at 0004H

    PIC has hardware stack with 8 bit width. It needs jump instruction toaccess subroutines. Push and Pop instructions cannot be used since there isno software stack is available.

    Program memory is organized as page 0, page 1 up to page 3 eachhaving 2k memories. Page address should be mentioned in PC latch forexecuting the instructions available in some other pages.

    Program memory Organization:

    0000H

    000 4H

    0005H

    07FFH0800H

    On-chipProgram memory

    0FFFH

    Reset Vector

    Interrupt Vector

    Page 0

    Page 1

    Page 2

    Page 3

    Program counter

    Stack level 1

    Stack level 2

    Stack level 8

  • 7/29/2019 Embedded System Microcontroller

    15/46

    1000H

    3FFFH

    Data Memory Organization:

    The data memory is partitioned into multiple banks which containgeneral purpose registers and special function registers.

    Each bank extends up to 7FH (128 bytes).The lower location of each

    bank are reserved for the special function register. Above the specialfunction registers are general purpose registers, implemented as Static RAM.

    In all banks the bottom most 16 bits are called accessed irrespective ofthe bank number.

    Data Memory Organization

    RP1 RP0 Bank no

    0 0 00 1 11 0 21 1 3

  • 7/29/2019 Embedded System Microcontroller

    16/46

    00 00 00

    1F 1F 1F20 20 20

    70 70 7071 71 71

    7F 7F 7F

    BANK 0 BANK 1 BANK 2

    BANK 3

    Status Register :

    The status register contains arithmetic status of ALU, Reset and bankselect bits for data memory.

    The bits Z, DC, C are set or reset according to the device logic.

    IRP RP1 RP0 TO PD Z DC C

    IRP Register Bank Selected bit.1 - Bank 2&30 - Bank 0 &1

    RP1.RP0 - Bank selection bitsTO - Time Out bit

    1 - After Power Up, CLRWDT instruction or SLEEP

    instruction0 - A WDT time out occurred

    PD - Power Down bit1 - After power up or by the CLRWDT instruction0 - By execution of the SLEEP instruction

    Z - Zero bit1 - The result of on arithmetic or logic operatio

    GPR

    SFR

    Accessbank

    GPR

    SFR

    Accessbank

    GPR

    SFR

    Accessbank

    GPR

    SFR

    Accessbank

  • 7/29/2019 Embedded System Microcontroller

    17/46

    0 - The result of on arithmetic or logic operation is not zeroDC - Digit carry / borrow bit

    1 - A carry out from the 4th low order bit of the resultoccurred

    0 - No carry out from the 4th low order bit the result.C - Carry / borrow bit

    1 - A carry out from the most significant bit of the resultoccurred

    0 - No carry-out from the most significant bit of the resultoccurred.

    INTCON REGISTER:

    The INTCON register is a readable and writable register which

    contains various enable and flag bits for the TMRO register overflow, RBport change and external RBO/INT pin interrupts.

    GIE PEIE TOIE INTE RBIE TOIF INTF RBIF

    Bit 7

    :

    GIE

    -

    Global interrupt Enable bit

    1-

    Enables all un masked interrupts

    0-

    Disable all interrupts

    Bit 6:

    PEIE-

    Peripheral interrupts Enable bit

    1-

    Enables all un un masked peripheral interrupts

    0

    -

    Disable all peripheral interrupts

    Bit 5:

    TOIE-

    TMRO Overflow Interrupt Enable bit

    1-

    Enables the TMRO interrupt

    0-

    Disable the TMRO interrupt

  • 7/29/2019 Embedded System Microcontroller

    18/46

    Bit 4:

    INTE-

    RBO/INT External interrupt Enable bit

    1-

    Enables the RBO/INT external interrupt

    0-

    Disable the RBO/ external Interrupt

    Bit3 :

    RBIE-

    RB port change Interrupt Enable bit

    1-

    Enables the RB port change interrupt

    0-

    Disable the RB port change interrupt

    Bit 2:

    TOIF-

    TMRO Overflow Interrupt Flag bit

    1-

    TMRO register has overflowed

    0-

    TMRO register did not over flow

    Bit 1:

    INTF-

    RBO/INT Enable Interrupt Flag bit

    1-

    The RBO/INT external Interrupt occurred

    0-

    The RBO/INT external interrupt did not occur

    Bit 0:

    RBIF-

    RB port Change Interrupt Flag bit

    1-

    At least one of the RB7 : RB4 pins changed sate

    0-

    None of the RB7 : RB4 pins have changed state

    OPTION REGISTER:

    RBPU INTEDG TOCS TOSE PSA PS2 PS1 PS0

    RBPU - Weak pull up Enable bit

  • 7/29/2019 Embedded System Microcontroller

    19/46

    INTEDG - Interrupt Edge select bit

    TOCS - Timer0 clock source select bit

    TOSE - Timer0 source edge select bit

    PSA - Pre scalar Assignment bit

    0 - Timer 0 is enabled

    1 - Watch dog timer is enabled

    PS2, PS1, PS0 - Pre scalar

    8051 Addressing Modes

    An "addressing mode" refers to how you are addressing a given memorylocation. In summary, the addressing modes are as follows, with an example

    of each: Immediate Addressing MOV A,#20h

    Direct Addressing MOV A,30h

    Indirect Addressing MOV A,@R0

    External Direct MOVX A,@DPTR

    Code Indirect MOVC A,@A+DPTR

    Each of these addressing modes provides important flexibility.

    Immediate Addressing

    Immediate addressing is so-named because the value to be stored in memoryimmediately follows the operation code in memory. That is to say, theinstruction itself dictates what value will be stored in memory.

    For example, the instruction:

  • 7/29/2019 Embedded System Microcontroller

    20/46

    MOV A,#20hThis instruction uses Immediate Addressing because the Accumulator will

    be loaded with the value that immediately follows; in this case 20(hexidecimal).

    Immediate addressing is very fast since the value to be loaded is included inthe instruction. However, since the value to be loaded is fixed at compile-time it is not very flexible.

    Direct Addressing

    Direct addressing is so-named because the value to be stored in memory isobtained by directly retrieving it from another memory location. Forexample:

    MOV A,30hThis instruction will read the data out of Internal RAM address 30(hexidecimal) and store it in the Accumulator.

    Direct addressing is generally fast since, although the value to be loadedisnt included in the instruction, it is quickly accessable since it is stored inthe 8051s Internal RAM. It is also much more flexible than ImmediateAddressing since the value to be loaded is whatever is found at the givenaddress--which may be variable.

    Also, it is important to note that when using direct addressing anyinstruction which refers to an address between 00h and 7Fh is referring toInternal Memory. Any instruction which refers to an address between 80hand FFh is referring to the SFR control registers that control the 8051microcontroller itself.

    The obvious question that may arise is, "If direct addressing an address from80h through FFh refers to SFRs, how can I access the upper 128 bytes ofInternal RAM that are available on the 8052?" The answer is: You cant

    access them using direct addressing. As stated, if you directly refer to anaddress of 80h through FFh you will be referring to an SFR. However, youmay access the 8052s upper 128 bytes of RAM by using the nextaddressing mode, "indirect addressing."

    Indirect Addressing

  • 7/29/2019 Embedded System Microcontroller

    21/46

    Indirect addressing is a very powerful addressing mode which in many casesprovides an exceptional level of flexibility. Indirect addressing is also theonly way to access the extra 128 bytes of Internal RAM found on an 8052.

    Indirect addressing appears as follows:

    MOV A,@R0This instruction causes the 8051 to analyze the value of the R0 register. The8051 will then load the accumulator with the value from Internal RAMwhich is found at the address indicated by R0.

    For example, lets say R0 holds the value 40h and Internal RAM address40h holds the value 67h. When the above instruction is executed the 8051will check the value of R0. Since R0 holds 40h the 8051 will get the value

    out of Internal RAM address 40h (which holds 67h) and store it in theAccumulator. Thus, the Accumulator ends up holding 67h.

    Indirect addressing always refers to Internal RAM; it never refers to an SFR.Thus, in a prior example we mentioned that SFR 99h can be used to write avalue to the serial port. Thus one may think that the following would be avalid solution to write the value 1 to the serial port:

    MOV R0,#99h ;Load the address of the serial portMOV @R0,#01h ;Send 01 to the serial port -- WRONG!!

    This is not valid. Since indirect addressing always refers to Internal RAMthese two instructions would write the value 01h to Internal RAM address99h on an 8052. On an 8051 these two instructions would produce anundefined result since the 8051 only has 128 bytes of Internal RAM.

    External Direct

    External Memory is accessed using a suite of instructions which use what Icall "External Direct" addressing. I call it this because it appears to be directaddressing, but it is used to access external memory rather than internal

    memory.

    There are only two commands that use External Direct addressing mode:

    MOVXA,@DPTR

    MOVX @DPTR,A

  • 7/29/2019 Embedded System Microcontroller

    22/46

    As you can see, both commands utilize DPTR. In these instructions, DPTRmust first be loaded with the address of external memory that you wish toread or write. Once DPTR holds the correct external memory address, thefirst command will move the contents of that external memory address intothe Accumulator. The second command will do the opposite: it will allowyou to write the value of the Accumulator to the external memory address

    pointed to by DPTR.

    External Indirect

    External memory can also be accessed using a form of indirect addressingwhich I call External Indirect addressing. This form of addressing is usuallyonly used in relatively small projects that have a very small amount ofexternal RAM. An example of this addressing mode is:

    MOVX @R0,AOnce again, the value of R0 is first read and the value of the Accumulator iswritten to that address in External RAM. Since the value of @R0 can only

    be 00h through FFh the project would effectively be limited to 256 bytes ofExternal RAM. There are relatively simple hardware/software tricks that can

    be implemented to access more than 256 bytes of memory using ExternalIndirect addressing; however, it is usually easier to use External Directaddressing if your project has more than 256 bytes of External RAM.8051 Program Flow

    When an 8051 is first initialized, it resets the PC to 0000h. The 8051 thenbegins to execute instructions sequentially in memory unless a programinstruction causes the PC to be otherwise altered. There are variousinstructions that can modify the value of the PC; specifically, conditional

    branching instructions, direct jumps and calls, and "returns" fromsubroutines. Additionally, interrupts, when enabled, can cause the programflow to deviate from its otherwise sequential scheme.

    Conditional Branching

    The 8051 contains a suite of instructions which, as a group, are referred to as"conditional branching" instructions. These instructions cause programexecution to follow a non-sequential path if a certain condition is true.

    Take, for example, the JB instruction. This instruction means "Jump if Bit Set." Anexample of the JB instruction might be:

  • 7/29/2019 Embedded System Microcontroller

    23/46

    JB 45h,HELLO

    NOP

    HELLO: ....

    In this case, the 8051 will analyze the contents of bit 45h. If the bit is set

    program execution will jump immediately to the label HELLO, skipping theNOP instruction. If the bit is not set the conditional branch fails and programexecution continues, as usual, with the NOP instruction which follows.

    Conditional branching is really the fundamental building block of programlogic since all "decisions" are accomplished by using conditional branching.Conditional branching can be thought of as the "IF...THEN" structure in8051 assembly language.

    An important note worth mentioning about conditional branching is that the

    program may only branch to instructions located withim 128 bytes prior toor 127 bytes following the address which follows the conditional branchinstruction. This means that in the above example the label HELLO must bewithin +/- 128 bytes of the memory address which contains the conditional

    branching instruction.

    Direct Jumps

    While conditional branching is extremely important, it is often necessary tomake a direct branch to a given memory location without basing it on a

    given logical decision. This is equivalent to saying "Goto" in BASIC. In thiscase you want the program flow to continue at a given memory addresswithout considering any conditions.

    This is accomplished in the 8051 using "Direct Jump and Call" instructions.As illustrated in the last paragraph, this suite of instructions causes programflow to change unconditionally.

    Consider the example:

    LJMP NEW_ADDRESS

    .

    .

    .

    NEW_ADDRESS: ....

  • 7/29/2019 Embedded System Microcontroller

    24/46

    The LJMP instruction in this example means "Long Jump." When the 8051executes this instruction the PC is loaded with the address of

    NEW_ADDRESS and program execution continues sequentially from there.

    The obvious difference between the Direct Jump and Call instructions andthe conditional branching is that with Direct Jumps and Calls program flowalways changes. With conditional branching program flow only changes if acertain condition is true.

    It is worth mentioning that, aside from LJMP, there are two otherinstructions which cause a direct jump to occur: the SJMP and AJMPcommands. Functionally, these two commands perform the exact samefunction as the LJMP command--that is to say, they always cause programflow to continue at the address indicated by the command. However, SJMP

    and AJMP differ in the following ways:

    The SJMP command, like the conditional branching instructions, canonly jump to an address within +/- 128 bytes of the SJMP command.

    The AJMP command can only jump to an address that is in the same2k block of memory as the AJMP command. That is to say, if theAJMP command is at code memory location 650h, it can only do a

    jump to addresses 0000h through 07FFh (0 through 2047, decimal).

    You may be asking yourself, "Why would I want to use the SJMP or AJMP

    command which have restrictions as to how far they can jump if they do thesame thing as the LJMP command which can jump anywhere in memory?"The answer is simple: The LJMP command requires three bytes of codememory whereas both the SJMP and AJMP commands require only two.Thus, if you are developing an application that has memory restrictions youcan often save quite a bit of memory using the 2-byte AJMP/SJMPinstructions instead of the 3-byte instruction.

    Recently, I wrote a program that required 2100 bytes of memory but I had amemory restriction of 2k (2048 bytes). I did a search/replace changing allLJMPs to AJMPs and the program shrunk downto 1950 bytes. Thus, withoutchanging any logic whatsoever in my program I saved 150 bytes and wasable to meet my 2048 byte memory restriction.

    NOTE: Some quality assemblers will actually do the above conversion foryou automatically. That is, theyll automatically change your LJMPs toSJMPs whenever possible. This is a nifty and very powerful capability that

  • 7/29/2019 Embedded System Microcontroller

    25/46

    you may want to look for in an assembler if you plan to develop manyprojects that have relatively tight memory restrictions.

    Direct Calls

    Another operation that will be familiar to seasoned programmers is theLCALL instruction. This is similar to a "Gosub" command in Basic.

    When the 8051 executes an LCALL instruction it immediately pushes thecurrent Program Counter onto the stack and then continues executing code atthe address indicated by the LCALL instruction.

    Returns from Routines

    Another structure that can cause program flow to change is the "Return fromSubroutine" instruction, known as RET in 8051 Assembly Language.

    The RET instruction, when executed, returns to the address following theinstruction that called the given subroutine. More accurately, it returns to theaddress that is stored on the stack.

    The RET command is direct in the sense that it always changes programflow without basing it on a condition, 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.

    Interrupts

    An interrupt is a special feature which allows the 8051 to provide theillusion of "multi-tasking," although in reality the 8051 is only doing onething at a time. The word "interrupt" can often be subsituted with the word"event."

    An interrupt is triggered whenever a corresponding event occurs. When the

    event occurs, the 8051 temporarily puts "on hold" the normal execution ofthe program and executes a special section of code referred to as an interrupthandler. The interrupt handler performs whatever special functions arerequired to handle the event and then returns control to the 8051 at which

    point program execution continues as if it had never been interrupted.

  • 7/29/2019 Embedded System Microcontroller

    26/46

    The topic of interrupts is somewhat tricky and very important. For thatreason, an entire chapter will be dedicated to the topic. For now, suffice it tosay that Interrupts can cause program flow to change.

    8051 Tutorial: Instruction Set, Timing, and Low-Level Info

    In order to understand--and better make use of--the 8051, it is necessary tounderstand some underlying information concerning timing.

    The 8051 operates based on an external crystal. This is an electrical devicewhich, when energy is applied, emits pulses at a fixed frequency. One canfind crystals of virtually any frequency depending on the applicationrequirements. When using an 8051, the most common crystal frequenciesare 12 megahertz and 11.059 megahertz--with 11.059 being much more

    common. Why would anyone pick such an odd-ball frequency? Theres areal reason for it--it has to do with generating baud rates and well talk moreabout it in the Serial Communication chapter. For the remainder of thisdiscussion well assume that were using an 11.059Mhz crystal.

    Microcontrollers (and many other electrical systems) use crystals tosyncrhronize operations. The 8051 uses the crystal for precisely that: tosynchronize its operation. Effectively, the 8051 operates using what arecalled "machine cycles." A single machine cycle is the minimum amount oftime in which a single 8051 instruction can be executed. although many

    instructions take multiple cycles.

    A cycle is, in reality, 12 pulses of the crystal. That is to say, if an instructiontakes one machine cycle to execute, it will take 12 pulses of the crystal toexecute. Since we know the crystal is pulsing 11,059,000 times per secondand that one machine cycle is 12 pulses, we can calculate how manyinstruction cycles the 8051 can execute per second:

    11,059,000 / 12 = 921,583This means that the 8051 can execute 921,583 single-cycle instructions persecond. Since a large number of 8051 instructions are single-cycleinstructions it is often considered that the 8051 can execute roughly 1million instructions per second, although in reality it is less--and, dependingon the instructions being used, an estimate of about 600,000 instructions persecond is more realistic.

  • 7/29/2019 Embedded System Microcontroller

    27/46

    For example, if you are using exclusively 2-cycle instructions you wouldfind that the 8051 would execute 460,791 instructions per second. The 8051also has two really slow instructions that require a full 4 cycles to execute--ifyou were to execute nothing but those instructions youd find performanceto be about 230,395 instructions per second.

    It is again important to emphasize that not all instructions execute in thesame amount of time. The fastest instructions require one machine cycle (12crystal pulses), many others require two machine cycles (24 crystal pulses),and the two very slow math operations require four machine cycles (48crystal pulses).

    NOTE: Many 8051 derivative chips change instruction timing. For example,many optimized versions of the 8051 execute instructions in 4 oscillator

    cycles instead of 12; such a chip would be effectively 3 times faster than the8051 when used with the same 11.059 Mhz crystal.

    Since all the instructions require different amounts of time to execute a veryobvious 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?

    Luckily, the 8051 includes timers which allow us to time events with highprecision--which is the topic of the next chapter.

    8051 Timers

    The 8051 comes equipped with two timers, both of which may be controlled,set, read, and configured individually. The 8051 timers have three generalfunctions: 1) Keeping time and/or calculating the amount of time betweenevents, 2) Counting the events themselves, or 3) Generating baud rates forthe serial port.

    The three timer uses are distinct so we will talk about each of themseparately. The first two uses will be discussed in this chapter while the useof timers for baud rate generation will be discussed in the chapter relating toserial ports.

    How does a timer count?

  • 7/29/2019 Embedded System Microcontroller

    28/46

    How does a timer count? The answer to this question is very simple: A timeralways counts up. It doesnt matter whether the timer is being used as atimer, a counter, or a baud rate generator: A timer is always incremented bythe microcontroller.

    Programming Tip: Some derivative chips actually allow the programto configure whether the timers count up or down. However, since thisoption only exists on some derivatives it is beyond the scope of thistutorial which is aimed at the standard 8051. It is only mentioned herein the event that you absolutely need a timer to count backwards, youwill know that you may be able to find an 8051-compatiblemicrocontroller that does it.

    USING TIMERS TO MEASURE TIME

    Obviously, one of the primary uses of timers is to measure time. We willdiscuss this use of timers first and will subsequently discuss the use oftimers to count events. When a timer is used to measure time it is also calledan "interval timer" since it is measuring the time of the interval between twoevents.

    How long does a timer take to count?

    First, its worth mentioning that when a timer is in interval timer mode (asopposed to event counter mode) and correctly configured, it will increment

    by 1 every machine cycle. As you will recall from the previous chapter, asingle machine cycle consists of 12 crystal pulses. Thus a running timer will

    be incremented:

    11,059,000 / 12 = 921,583921,583 times per second. Unlike instructions--some of which require 1machine cycle, others 2, and others 4--the timers are consistent: They willalways be incremented once per machine cycle. Thus if a timer has countedfrom 0 to 50,000 you may calculate:

    50,000 / 921,583 = .0542.0542 seconds have passed. In plain English, about half of a tenth of asecond, or one-twentieth of a second.

    Obviously its not very useful to know .0542 seconds have passed. If youwant to execute an event once per second youd have to wait for the timer tocount from 0 to 50,000 18.45 times. How can you wait "half of a time?" Youcant. So we come to another important calculation.

  • 7/29/2019 Embedded System Microcontroller

    29/46

    Lets say we want to know how many times the timer will be incremented in.05 seconds. We can do simple multiplication:

    .05 * 921,583 = 46,079.15.This tells us that it will take .05 seconds (1/20th of a second) to count from 0to 46,079. Actually, it will take it .049999837 seconds--so were off by .000000163 seconds--however, thats close enough for government work.Consider that if you were building a watch based on the 8051 and made theabove assumption your watch would only gain about one second every 2months. Again, I think thats accurate enough for most applications--I wishmy watch only gained one second every two months!

    Obviously, this is a little more useful. If you know it takes 1/20th of asecond to count from 0 to 46,079 and you want to execute some event every

    second you simply wait for the timer to count from 0 to 46,079 twentytimes; then you execute your event, reset the timers, and wait for the timer tocount up another 20 times. In this manner you will effectively execute yourevent once per second, accurate to within thousandths of a second.

    Thus, we now have a system with which to measure time. All we need toreview is how to control the timers and initialize them to provide us with theinformation we need.

    Timer SFRs

    As mentioned before, the 8051 has two timers which each functionessentially the same way. One timer is TIMER0 and the other is TIMER1.The two timers share two SFRs (TMOD and TCON) which control thetimers, and each timer also has two SFRs dedicated solely to itself(TH0/TL0 and TH1/TL1).

    Weve given SFRs names to make it easier to refer to them, but in reality anSFR has a numeric address. It is often useful to know the numeric addressthat corresponds to an SFR name. The SFRs relating to timers are:

    SFR Name Description SFR Address

    TH0 Timer 0 High Byte 8Ch

    TL0 Timer 0 Low Byte 8Ah

    TH1 Timer 1 High Byte 8Dh

  • 7/29/2019 Embedded System Microcontroller

    30/46

    TL1 Timer 1 Low Byte 8Bh

    TCON Timer Control 88h

    TMOD Timer Mode 89h

    When you enter the name of an SFR into an assembler, it internally convertsit to a number. For example, the command:

    MOV TH0,#25hmoves the value 25h into the TH0 SFR. However, since TH0 is the same asSFR address 8Ch this command is equivalent to:

    MOV 8Ch,#25hNow, back to the timers. First, lets talk about Timer 0.

    Timer 0 has two SFRs dedicated exclusively to itself: TH0 and TL0.Without making things too complicated to start off with, you may just thinkof this as the high and low byte of the timer. That is to say, when Timer 0has a value of 0, both TH0 and TL0 will contain 0. When Timer 0 has thevalue 1000, TH0 will hold the high byte of the value (3 decimal) and TL0will contain the low byte of the value (232 decimal). Reviewing low/high

    byte notation, recall that you must multiply the high byte by 256 and add thelow byte to calculate the final value. That is to say:

    TH0 * 256 + TL0 = 1000

    3 * 256 + 232 = 1000Timer 1 works the exact same way, but its SFRs are TH1 and TL1.

    Since there are only two bytes devoted to the value of each timer it isapparent that the maximum value a timer may have is 65,535. If a timercontains the value 65,535 and is subsequently incremented, it will reset--oroverflow--back to 0.

    The TMOD SFR

    Lets first talk about our first control SFR: TMOD (Timer Mode). TheTMOD SFR is used to control the mode of operation of both timers. Each bitof the SFR gives the microcontroller specific information concerning how torun a timer. The high four bits (bits 4 through 7) relate to Timer 1 whereasthe low four bits (bits 0 through 3) perform the exact same functions, but fortimer 0.

  • 7/29/2019 Embedded System Microcontroller

    31/46

    The individual bits of TMOD have the following functions:

    TMOD (89h) SFR

    Bit Name Explanation of Function Timer

    7 GATE1When this bit is set the timer will onlyrun when INT1 (P3.3) is high. When this

    bit is clear the timer will run regardlessof the state of INT1.

    1

    6 C/T1

    When this bit is set the timer will countevents on T1 (P3.5). When this bit isclear the timer will be incremented everymachine cycle.

    1

    5 T1M1 Timer mode bit (see below) 1

    4 T1M0 Timer mode bit (see below) 1

    3 GATE0

    When this bit is set the timer will onlyrun when INT0 (P3.2) is high. When this

    bit is clear the timer will run regardlessof the state of INT0.

    0

    2 C/T0

    When this bit is set the timer will countevents on T0 (P3.4). When this bit isclear the timer will be incremented everymachine cycle.

    0

    1 T0M1 Timer mode bit (see below) 0

    0 T0M0 Timer mode bit (see below) 0

    As you can see in the above chart, four bits (two for each timer) are used tospecify a mode of operation. The modes of operation are:

    TxM1 TxM0 Timer Mode Description of Mode

    0 0 0 13-bit Timer.

    0 1 1 16-bit Timer

    1 0 2 8-bit auto-reload

    1 1 3 Split timer mode

    13-bit Time Mode (mode 0)

  • 7/29/2019 Embedded System Microcontroller

    32/46

    Timer mode "0" is a 13-bit timer. This is a relic that was kept around in the8051 to maintain compatability with its predecesor, the 8048. Generally the13-bit timer mode is not used in new development.

    When the timer is in 13-bit mode, TLx will count from 0 to 31. When TLx isincremented from 31, it will "reset" to 0 and increment THx. Thus,effectively, only 13 bits of the two timer bytes are being used: bits 0-4 ofTLx and bits 0-7 of THx. This also means, in essence, the timer can onlycontain 8192 values. If you set a 13-bit timer to 0, it will overflow back tozero 8192 machine cycles later.

    Again, there is very little reason to use this mode and it is only mentioned soyou wont be surprised if you ever end up analyzing archaeic code which has

    been passed down through the generations (a generation in a programming

    shop is often on the order of about 3 or 4 months).

    16-bit Time Mode (mode 1)

    Timer mode "1" is a 16-bit timer. This is a very commonly used mode. Itfunctions just like 13-bit mode except that all 16 bits are used.

    TLx is incremented from 0 to 255. When TLx is incremented from 255, itresets to 0 and causes THx to be incremented by 1. Since this is a full 16-bittimer, the timer may contain up to 65536 distinct values. If you set a 16-bit

    timer to 0, it will overflow back to 0 after 65,536 machine cycles.

    8-bit Time Mode (mode 2)

    Timer mode "2" is an 8-bit auto-reload mode. What is that, you may ask?Simple. When a timer is in mode 2, THx holds the "reload value" and TLx isthe timer itself. Thus, TLx starts counting up. When TLx reaches 255 and issubsequently incremented, instead of resetting to 0 (as in the case of modes0 and 1), it will be reset to the value stored in THx.

    For example, lets say TH0 holds the value FDh and TL0 holds the valueFEh. If we were to watch the values of TH0 and TL0 for a few machinecycles this is what wed see:

    Machine Cycle TH0 Value TL0 Value

    1 FDh FEh

  • 7/29/2019 Embedded System Microcontroller

    33/46

    2 FDh FFh

    3 FDh FDh

    4 FDh FEh

    5 FDh FFh

    6 FDh FDh

    7 FDh FEh

    As you can see, the value of TH0 never changed. In fact, when you usemode 2 you almost always set THx to a known value and TLx is the SFRthat is constantly incremented.

    Whats the benefit of auto-reload mode? Perhaps you want the timer toalways have a value from 200 to 255. If you use mode 0 or 1, youd have tocheck in code to see if the timer had overflowed and, if so, reset the timer to200. This takes precious instructions of execution time to check the valueand/or to reload it. When you use mode 2 the microcontroller takes care ofthis for you. Once youve configured a timer in mode 2 you dont have toworry about checking to see if the timer has overflowed nor do you have toworry about resetting the value--the microcontroller hardware will do it allfor you.

    The auto-reload mode is very commonly used for establishing a baud rate

    which we will talk more about in the Serial Communications chapter.

    Split Timer Mode (mode 3)

    Timer mode "3" is a split-timer mode. When Timer 0 is placed in mode 3, itessentially becomes two separate 8-bit timers. That is to say, Timer 0 is TL0and Timer 1 is TH0. Both timers count from 0 to 255 and overflow back to0. All the bits that are related to Timer 1 will now be tied to TH0.

    While Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be

    put into modes 0, 1 or 2 normally--however, you may not start or stop thereal timer 1 since the bits that do that are now linked to TH0. The real timer1, in this case, will be incremented every machine cycle no matter what.

    The only real use I can see of using split timer mode is if you need to havetwo separate timers and, additionally, a baud rate generator. In such case you

  • 7/29/2019 Embedded System Microcontroller

    34/46

    can use the real Timer 1 as a baud rate generator and use TH0/TL0 as twoseparate timers.

    The TCON SFR

    Finally, theres one more SFR that controls the two timers and providesvaluable information about them. The TCON SFR has the followingstructure:

    TCON (88h) SFR

    Bit NameBit

    AddressExplanation of Function Timer

    7 TF1 8FhTimer 1 Overflow. This bit is set by themicrocontroller when Timer 1 overflows.

    1

    6 TR1 8EhTimer 1 Run. When this bit is set Timer1 is turned on. When this bit is clearTimer 1 is off.

    1

    5 TF0 8DhTimer 0 Overflow. This bit is set by themicrocontroller when Timer 0 overflows.

    0

    4 TR0 8ChTimer 0 Run. When this bit is set Timer0 is turned on. When this bit is clearTimer 0 is off.

    0

    As you may notice, weve only defined 4 of the 8 bits. Thats because theother 4 bits of the SFR dont have anything to do with timers--they have todo with Interrupts and they will be discussed in the chapter that addressesinterrupts.

    A new piece of information in this chart is the column "bit address." This isbecause this SFR is "bit-addressable." What does this mean? It means if youwant to set the bit TF1--which is the highest bit of TCON--you couldexecute the command:

    MOV TCON, #80h... or, since the SFR is bit-addressable, you could just execute the command:

    SETB TF1This has the benefit of setting the high bit of TCON without changing thevalue of any of the other bits of the SFR. Usually when you start or stop atimer you dont want to modify the other values in TCON, so you takeadvantage of the fact that the SFR is bit-addressable.

  • 7/29/2019 Embedded System Microcontroller

    35/46

    Initializing a Timer

    Now that weve discussed the timer-related SFRs we are ready to write codethat will initialize the timer and start it running.

    As youll recall, we first must decide what mode we want the timer to be in.In this case we want a 16-bit timer that runs continuously; that is to say, it isnot dependent on any external pins.

    We must first initialize the TMOD SFR. Since we are working with timer 0we will be using the lowest 4 bits of TMOD. The first two bits, GATE0 andC/T0 are both 0 since we want the timer to be independent of the external

    pins. 16-bit mode is timer mode 1 so we must clear T0M1 and set T0M0.Effectively, the only bit we want to turn on is bit 0 of TMOD. Thus to

    initialize the timer we execute the instruction:

    MOV TMOD,#01hTimer 0 is now in 16-bit timer mode. However, the timer is not running. Tostart the timer running we must set the TR0 bit We can do that by executingthe instruction:

    SETB TR0Upon executing these two instructions timer 0 will immediately begincounting, being incremented once every machine cycle (every 12 crystal

    pulses).

    Reading the Timer

    There are two common ways of reading the value of a 16-bit timer; whichyou use depends on your specific application. You may either read the actualvalue of the timer as a 16-bit number, or you may simply detect when thetimer has overflowed.

    Reading the value of a Timer

    If your timer is in an 8-bit mode--that is, either 8-bit AutoReload mode or insplit timer mode--then reading the value of the timer is simple. You simplyread the 1-byte value of the timer and youre done.

    However, if youre dealing with a 13-bit or 16-bit timer the chore is a littlemore complicated. Consider what would happen if you read the low byte ofthe timer as 255, then read the high byte of the timer as 15. In this case, what

  • 7/29/2019 Embedded System Microcontroller

    36/46

    actually happened was that the timer value was 14/255 (high byte 14, lowbyte 255) but you read 15/255. Why? Because you read the low byte as 255.But when you executed the next instruction a small amount of time passed--

    but enough for the timer to increment again at which time the value rolledover from 14/255 to 15/0. But in the process youve read the timer as being15/255. Obviously theres a problem there.

    The solution? Its not too tricky, really. You read the high byte of the timer,then read the low byte, then read the high byte again. If the high byte readthe second time is not the same as the high byte read the first time you repeatthe cycle. In code, this would appear as:

    REPEAT: MOV A,TH0

    MOV R0,TL0

    CJNE A,TH0,REPEAT...

    In this case, we load the accumulator with the high byte of Timer 0. We thenload R0 with the low byte of Timer 0. Finally, we check to see if the high

    byte we read out of Timer 0--which is now stored in the Accumulator--is thesame as the current Timer 0 high byte. If it isnt it means weve just "rolledover" and must reread the timers value--which we do by going back toREPEAT. When the loop exits we will have the low byte of the timer in R0and the high byte in the Accumulator.

    Another much simpler alternative is to simply turn off the timer run bit (i.e.CLR TR0), read the timer value, and then turn on the timer run bit (i.e.SETB TR0). In that case, the timer isnt running so no special tricks arenecessary. Of course, this implies that your timer will be stopped for a fewmachine cycles. Whether or not this is tolerable depends on your specificapplication.

    Detecting Timer Overflow

    Often it is necessary to just know that the timer has reset to 0. That is to say,you are not particularly interest in the value of the timer but rather you areinterested in knowing when the timer has overflowed back to 0.

    Whenever a timer overflows from its highest value back to 0, themicrocontroller automatically sets the TFx bit in the TCON register. This isuseful since rather than checking the exact value of the timer you can just

  • 7/29/2019 Embedded System Microcontroller

    37/46

    check if the TFx bit is set. If TF0 is set it means that timer 0 has overflowed;if TF1 is set it means that timer 1 has overflowed.

    We can use this approach to cause the program to execute a fixed delay. Asyoull recall, we calculated earlier that it takes the 8051 1/20th of a second tocount from 0 to 46,079. However, the TFx flag is set when the timeroverflows back to 0. Thus, if we want to use the TFx flag to indicate when1/20th of a second has passed we must set the timer initially to 65536 less46079, or 19,457. If we set the timer to 19,457, 1/20th of a second later thetimer will overflow. Thus we come up with the following code to execute a

    pause of 1/20th of a second:

    MOV TH0,#76;High byte of 19,457 (76 * 256 = 19,456)MOV TL0,#01;Low byte of 19,457 (19,456 + 1 = 19,457)

    MOV TMOD,#01;Put Timer 0 in 16-bit modeSETB TR0;Make Timer 0 start countingJNB TF0,$;If TF0 is not set, jump back to this same instruction

    In the above code the first two lines initialize the Timer 0 starting value to19,457. The next two instructions configure timer 0 and turn it on. Finally,the last instruction JNB TF0,$, reads "Jump, if TF0 is not set, back to thissame instruction." The "$" operand means, in most assemblers, the addressof the current instruction. Thus as long as the timer has not overflowed andthe TF0 bit has not been set the program will keep executing this sameinstruction. After 1/20th of a second timer 0 will overflow, set the TF0 bit,

    and program execution will then break out of the loop.

    Timing the length of events

    The 8051 provides another cool toy that can be used to time the length ofevents.

    For example, let's say we're trying to save electricity in the office and we'reinterested in how long a light is turned on each day. When the light is turnedon, we want to measure time. When the light is turned off we don't. Oneoption would be to connect the lightswitch to one of the pins, constantly readthe pin, and turn the timer on or off based on the state of that pin. While thiswould work fine, the 8051 provides us with an easier method ofaccomplishing this.

    Looking again at the TMOD SFR, there is a bit called GATE0. So far we'vealways cleared this bit because we wanted the timer to run regardless of the

  • 7/29/2019 Embedded System Microcontroller

    38/46

    state of the external pins. However, now it would be nice if an external pincould control whether the timer was running or not. It can. All we need to dois connect the lightswitch to pin INT0 (P3.2) on the 8051 and set the bitGATE0. When GATE0 is set Timer 0 will only run if P3.2 is high. WhenP3.2 is low (i.e., the lightswitch is off) the timer will automatically bestopped.

    Thus, with no control code whatsoever, the external pin P3.2 can controlwhether or not our timer is running or not.

    USING TIMERS AS EVENT COUNTERS

    We've discussed how a timer can be used for the obvious purpose of keepingtrack of time. However, the 8051 also allows us to use the timers to count

    events.

    How can this be useful? Let's say you had a sensor placed across a road thatwould send a pulse every time a car passed over it. This could be used todetermine the volume of traffic on the road. We could attach this sensor toone of the 8051's I/O lines and constantly monitor it, detecting when it

    pulsed high and then incrementing our counter when it went back to a lowstate. This is not terribly difficult, but requires some code. Let's say wehooked the sensor to P1.0; the code to count cars passing would looksomething like this:

    JNB P1.0,$ ;If a car hasn't raised the signal, keep waiting

    JB P1.0,$;The line is high which means the car is on the sensorright now

    INCCOUNTER

    ;The car has passed completely, so we count it

    As you can see, it's only three lines of code. But what if you need to bedoing other processing at the same time? You can't be stuck in the JNBP1.0,$ loop waiting for a car to pass if you need to be doing other things. Of

    course, there are ways to get around even this limitation but the code quicklybecomes big, complex, and ugly.

    Luckily, since the 8051 provides us with a way to use the timers to countevents we don't have to bother with it. It is actually painfully easy. We onlyhave to configure one additional bit.

  • 7/29/2019 Embedded System Microcontroller

    39/46

    Let's say we want to use Timer 0 to count the number of cars that pass. Ifyou look back to the bit table for the TCON SFR you will there is a bitcalled "C/T0"--it's bit 2 (TCON.2). Reviewing the explanation of the bit wesee that if the bit is clear then timer 0 will be incremented every machinecycle. This is what we've already used to measure time. However, if we setC/T0 timer 0 will monitor the P3.4 line. Instead of being incremented everymachine cycle, timer 0 will count events on the P3.4 line. So in our case wesimply connect our sensor to P3.4 and let the 8051 do the work. Then, whenwe want to know how many cars have passed, we just read the value oftimer 0--the value of timer 0 will be the number of cars that have passed.

    So what exactly is an event? What does timer 0 actually "count?" Speakingat the electrical level, the 8051 counts 1-0 transitions on the P3.4 line. Thismeans that when a car first runs over our sensor it will raise the input to a

    high ("1") condition. At that point the 8051 will not count anything sincethis is a 0-1 transition. However, when the car has passed the sensor will fall

    back to a low ("0") state. This is a 1-0 transition and at that instant thecounter will be incremented by 1.

    It is important to note that the 8051 checks the P3.4 line each instructioncycle (12 clock cycles). This means that if P3.4 is low, goes high, and goes

    back low in 6 clock cycles it will probably not be detected by the 8051. Thisalso means the 8051 event counter is only capable of counting events thatoccur at a maximum of 1/24th the rate of the crystal frequency. That is to

    say, if the crystal frequency is 12.000 Mhz it can count a maximum of500,000 events per second (12.000 Mhz * 1/24 = 500,000). If the event

    being counted occurs more than 500,000 times per second it will not be ableto be accurately counted by the 8051.

    DESCRIPTION OF AT89C51:

    The AT89C51 is a low-power, high-performance CMOS 8-bit

    microcomputer with 4K bytes of Flash programmable and erasable read only

    memory (PEROM). The device is manufactured using Atmels high-density

    nonvolatile memory technology and is compatible with the industry-standard

    MCS-51 instruction set and pinout. The on-chip Flash allows the program

  • 7/29/2019 Embedded System Microcontroller

    40/46

    memory to be reprogrammed in-system or by a conventional nonvolatile

    memory programmer. By combining a versatile 8-bit CPU with Flash on a

    monolithic chip, the Atmel AT89C51 is a powerful microcomputer which

    provides a highly-flexible and cost-effective solution to many embedded

    control applications.

    The AT89C51 provides the following standard features: 4K bytes of

    Flash, 128 bytes of RAM, 32 I/O lines, two 16-bit timer/counters, five vector

    two-level interrupt architecture, a full duplex serial port, and on-chip

    oscillator and clock circuitry. In addition, the AT89C51 is designed with

    static logic for operation down to zero frequency and supports two software

    selectable power saving modes. The Idle Mode stops the CPU while

    allowing the RAM, timer/counters, serial port and interrupt system to

    continue functioning. The Power-down Mode saves the RAM contents but

    freezes the oscillator disabling all other chip functions until the next

    hardware reset.

    OSCILLATOR CHARACTERISTICS:

    XTAL1 and XTAL2 are the input and output, respectively, of an

    inverting amplifier which can be configured for use as an on-chip oscillator;

    Either a quartz crystal or ceramic resonator may be used. To drive the device

    from an external clock source, XTAL2 should be left unconnected while

    XTAL1 is driven. There are no requirements on the duty cycle of theexternal clock signal, since the input to the internal clocking circuitry is

    through a divide-by-two flip-flop, but minimum and maximum voltage high

    and low time specifications must be observed.

  • 7/29/2019 Embedded System Microcontroller

    41/46

    IDLE MODE:

    In idle mode, the CPU puts itself to sleep while all the on chip

    peripherals remain active. The mode is invoked by software. The content of

    the on-chip RAM and all the special functions registers remain unchanged

    during this mode. The idle mode can be terminated by any enabled interrupt

    or by a hardware reset. It should be noted that when idle is terminated by a

    hard ware reset, the device normally resumes program execution, from

    where it left off, up to two machine cycles before

    the internal reset algorithm takes control. On-chip hardware inhibits access

    to internal RAM in this event, but access to the port pins is not inhibited. To

    eliminate the possibility of an unexpected write to a port pin when Idle is

    terminated by

    Reset, the instruction following the one that invokes Idle should not be one

    that writes to a port pin or to external memory.

  • 7/29/2019 Embedded System Microcontroller

    42/46

    3.3.2 PIN DIAGRAM OF AT89C51

    AT 89C51

  • 7/29/2019 Embedded System Microcontroller

    43/46

    3.3.3 PIN DESCRIPTION

    VCC:

    Supply voltage.

    GND:

    Ground.

    Port 0:

    Port 0 is an 8-bit open-drain bi-directional I/O port. As an output port,

    each pin can sink eight TTL inputs. When 1s are written to port 0 pins, the

    pins can be used as high impedance inputs. Port 0 may also be configured to

    be the multiplexed low order address/data bus during accesses to external

    program and data memory. In this mode P0 has internal pull-ups. Port 0 also

    receives the code bytes during Flash programming, and outputs the code

    bytes during program verification. External pull-ups are required during

    program verification.

    Port 1:

    Port 1 is an 8-bit bi-directional I/O port with internal pull-ups. The

    Port 1 output buffers can sink/source four TTL inputs. When 1s are written

    to Port 1 pins they are pulled high by the internal pull-ups and can be used as

    inputs. As inputs, Port 1 pins that are externally being pulled low will source

  • 7/29/2019 Embedded System Microcontroller

    44/46

    current (IIL) because of the internal pull-ups. Port 1 also receives the low-

    order address bytes during Flash programming and verification.

    Port 2:

    Port 2 is an 8-bit bi-directional I/O port with internal pull-ups. The

    Port 2 output buffers can sink/source four TTL inputs. When 1s are written

    to Port 2 pins they are pulled high by the internal pull-ups and can be used as

    inputs.

    Port 2 pins that are externally being pulled low will source current (IIL)

    because of the internal pull-ups.

    RST:

    Reset input a high on this pin for two machine cycles while the

    oscillator is running resets the device.

    ALE/PROG:

    Address Latch Enable output pulse for latching the low byte of the

    address during accesses to external memory. This pin is also the program

    pulse input (PROG) during Flash programming. In normal operation ALE is

    emitted at a constant rate of 1/6 the oscillator frequency, and may be used

    for external timing or clocking purposes. Note, however, that one ALE pulse

    is skipped during each access to external Data Memory.

    PSEN:

  • 7/29/2019 Embedded System Microcontroller

    45/46

    Program Store Enable is the read strobe to external program memory.

    When the AT89C51 is executing code from external program memory,

    PSEN is activated twice each machine cycle, except that two PSEN

    activations are skipped during

    each access to external data memory.

    EA/VPP:

    External Access Enable. EA must be strapped to GND in order to

    enable the device to fetch code from external program memory locations

    starting at 0000H up to FFFFH. Note, however, that if lock bit 1 is

    programmed, EA will be

    internally latched on reset. EA should be strapped to VCC for internal

    program

    executions. This pin also receives the 12volt programming enable voltage

    (VPP) during Flash programming, for parts that require 12-volt VPP.

    XTAL1:

    Input to the inverting oscillator amplifier and input to the internal

    clock operating circuit.

    XTAL2:

    Output from the inverting oscillator amplifier.

    Port Pin Alternate Functions

    P3.0

    P3.1

    RXD (serial input port)

    TXD (serial output port)

  • 7/29/2019 Embedded System Microcontroller

    46/46

    P3.2

    P3.3

    P3.4

    P3.5

    P3.6

    P3.7

    INT0 (external interrupt 0)

    INT1 (external interrupt 1)

    T0 (timer 0 external input)

    T1 (timer 1 external input)

    WR (external data memory write strobe)

    RD (external data memory read strobe)