8051 Material
8051 Material
____________________________________________________________________________________________________________
Head Office: #502, Naga Suri Plaza, Beside Minerva coffee shop, Behind Maithrivanam, Ameerpet,
Hyderabad 500016 Tel: 91-40-2373 6669, Cell: 98 66 66 66 99
[email protected] , www.vectorindia.org
_________________________________________________________________________________
www.vectorindia.org 1
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Chapter 1
Chapter 1 ................................................................................................................................................ 2
Microcontrollers ..................................................................................................................................... 5
Introduction ........................................................................................................................................ 5
Microprocessor .................................................................................................................................. 5
Microcontroller .................................................................................................................................. 6
Microcontrollers and Microprocessors .............................................................................................. 7
Block Diagram of Microcontroller .................................................................................................... 8
Central Processing Unit (CPU) ...................................................................................................... 8
I/O (Input/output) devices .............................................................................................................. 8
Memory .......................................................................................................................................... 8
Example ............................................................................................................................................. 9
Bus Unit ............................................................................................................................................. 9
Address bus .................................................................................................................................. 10
Data bus ....................................................................................................................................... 10
Control bus ................................................................................................................................... 10
Registers ........................................................................................................................................... 11
ALU (arithmetic/logic unit) ............................................................................................................. 11
Program counter ............................................................................................................................... 11
Instruction decoder........................................................................................................................... 12
Comparing Microprocessors and Microcontrollers ......................................................................... 12
Types of Microcontrollers................................................................................................................ 13
The 8-Bit Microcontroller ............................................................................................................ 13
The 16-Bit Microcontroller .......................................................................................................... 13
The 32-Bit Microcontroller .......................................................................................................... 13
Microcontroller Architectural Features............................................................................................ 14
Von-Neuman Architecture ........................................................................................................... 14
Harvard Architecture ................................................................................................................... 15
CISC (Complex Instruction Set Computer) Architecture ............................................................ 15
RISC (Reduced Instruction Set Computer) Architecture............................................................. 16
Commercial Microcontroller Devices.............................................................................................. 17
Micro-coded processor..................................................................................................................... 17
Hardwired processor ........................................................................................................................ 17
8051 Microcontroller ........................................................................................................................... 18
Features ............................................................................................................................................ 18
Block Diagram of 8051 .................................................................................................................... 19
8051 Pin Diagram ............................................................................................................................ 20
PIN Description of 8051 .................................................................................................................. 21
Crystal Circuit .............................................................................................................................. 22
RESET (RST) .............................................................................................................................. 22
_________________________________________________________________________________
www.vectorindia.org 2
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 3
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 4
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Microcontrollers
Introduction
Microcontrollers have only been with us for a few decades but their impact (direct or indirect) on our
lives is profound. Usually these are supposed to be just data processors are performing exhaustive
numeric operations but their presence is unnoticed at most of the places like
At supermarkets in Cash Registers, Weighing Scales, etc.
At home in Ovens, Washing Machines, Alarm Clocks, etc…
At play in Toys, VCRs, Stereo Equipment, etc.
At office in Typewriters, Photocopiers, Elevators, etc…
In industry in Industrial Automation, safety systems, etc…
On roads in Cars, Traffic Signals, etc.
Simply an embedded controller is a controller that is embedded in a greater system. One can define
an embedded controller as a controller (or computer) that is embedded into some device for some
purpose other than to provide general purpose computing. Some devices like 68000, 32032, x86,
Z80, and so on that are used as embedded controllers but they are not microcontrollers.
Example
For suppose if we want to control a device such as a microwave oven, car braking system or a cruise
missile. An embedded controller may also embed on the on-chip resources like a microcontroller.
Microcontrollers and microprocessors are widely used in embedded systems. However, we preferred
microcontrollers to microprocessors for embedded systems due to low power consumption.
If we want to know about microcontroller first of all we have to know General purpose
Microprocessor and Microcontroller.
Microprocessor
This is a normal CPU (Central Processing Unit) as you can find in a PC. Communication with
external devices is achieved via a data bus, hence the chip mainly features data and address pins as
well as a couple of control pins.
_________________________________________________________________________________
www.vectorindia.org 5
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
All peripheral devices (memory, floppy controller, USB controller, timer . . .) are connected to the
bus. A microprocessor cannot be operated stand-alone; at the very least it requires some memory and
an output device to be useful.
Please note that a processor is no controller. Nevertheless, some manufacturers and vendors list their
controllers under the term “microprocessor”. In this text we use the term processor just for the
processor core (the CPU) of a microcontroller.
Must add RAM, ROM, I/O ports, and timers externally to make them functional
Make the system bulkier and much more expensive
Have the advantage of versatility on the amount of RAM, ROM, and I/O ports
Microcontroller
A microcontroller already contains all components which allow it to operate standalone, and it has
been designed in particular for monitoring and/or control tasks. In consequence, in addition to the
processor it includes memory, various interface controllers, one or more timers, an interrupt
controller, and last but definitely not least general purpose I/O pins which allow it to directly
interface to its environment. Microcontrollers also include bit operations which allow you to change
one bit within a byte without touching the other bits.
The fixed amount of on-chip ROM, RAM, and number of I/O ports makes them ideal for
many applications in which cost and space are critical
In many applications, the space it takes, the power it consumes, and the price per unit are
much more critical considerations than the computing power
An embedded product uses a microprocessor (or microcontroller) to do one task and one task
only
There is only one application software that is typically burned into ROM
A PC, in contrast with the embedded system, can be used for any number of applications
It has RAM memory and an operating system that loads a variety of applications into
RAM and lets the CPU run them
A PC contains or is connected to various embedded products
Each one peripheral has a microcontroller inside it that performs only one task
A digital computer having microprocessor as the CPU along with I/O devices and memory is known
as microcomputer.
_________________________________________________________________________________
www.vectorindia.org 6
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
A microcontroller is a highly integrated chip, which includes on single chip, all or most of the parts
needed for a controller. The microcontroller typically includes: CPU (Central Processing Unit),
RAM (Random Access Memory), EPROM/PROM/ROM (Erasable Programmable Read Only
Memory), I/O (input/output) – serial and parallel, timers, interrupt controller. For example, Intel
8051 is 8-bit microcontroller and Intel 8096 is 16-bit microcontroller.
By only including the features specific to the task (control), cost is relatively low. A typical
microcontroller has bit manipulation instructions, easy and direct access to I/O (input/output), and
quick and efficient interrupt processing. Figure 1.3 shows the block diagram of a typical
microcontroller.
A CPU built into a single VLSI chip is called microprocessor. It contains arithmetic and logic unit
(ALU), Instruction decodes and control unit, Instruction register, Program counter (PC), clock circuit
(internal or external), reset circuit (internal or external) and registers. For example, Intel 8085 is 8-bit
microprocessor and Intel 8086/8088 is 16-bit microprocessor. Microprocessor is general-purpose
digital computer central processing unit (CPU).The microprocessor is general- Microprocessor is
general-purpose digital computer central processing unit (CPU).
_________________________________________________________________________________
www.vectorindia.org 7
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Memory
RAM (Random Access Memory) - Temporary storage of programs that computer is running and
the data is lost when computer is off
ROM (Read Only Memory) – contains programs and information essential to operation of the
computer and the information cannot be changed by use, and is not lost when power is off
– It is called nonvolatile memory
_________________________________________________________________________________
www.vectorindia.org 8
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
EEPROM (also written E2PROM and pronounced "e-e-prom," "double-e prom," "e-squared," or
simply "e-prom") stands for Electrically Erasable Programmable Read-Only
Memory and is a type of non-volatile memory used in computers and other electronic devices to
store small amounts of data that must be saved when power is removed,
Example
Calibration tables
Device configuration
When larger amounts of static data are to be stored (such as in USB flash drives) a specific type of
EEPROM such as flash memory is more economical than traditional EEPROM devices. EEPROMs
are realized as arrays of floating-gate transistors.
EEPROM is user-modifiable read-only memory (ROM) that can be erased and reprogrammed
(written to) repeatedly through the application of higher than normal electrical voltage generated
externally or internally in the case of modern EEPROMs
Bus Unit
The CPU is connected to memory and I/O through strips of wire called a bus
Carries information from place to place
Address bus
Data bus
Control bus
_________________________________________________________________________________
www.vectorindia.org 9
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Address bus
For a device (memory or I/O) to be recognized by the CPU, it must be assigned an address
The address assigned to a given device must be unique
The CPU puts the address on the address bus, and the decoding circuitry finds the device
The address bus is unidirectional
Data bus
The CPU either gets data from the device or sends data to it
Data buses are bidirectional
Control bus
Provides read or write signals to the device to indicate if the CPU is asking for information or
sending it information
For the CPU to process information, the data must be stored in RAM or ROM, which are
referred to as primary memory
ROM provides information that is fixed and permanent
Tables or initialization program
RAM stores information that is not permanent and can change with time
Various versions of OS and application packages
CPU gets information to be processed
o first form RAM (or ROM)
o if it is not there, then seeks it from a mass storage device, called secondary
memory, and transfers the information to RAM
_________________________________________________________________________________
www.vectorindia.org 10
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Registers
The CPU uses registers to store information temporarily
Values to be processed
Address of value to be fetched from memory
Registers can be 8-, 16-, 32-, or 64-bit
The disadvantage of more and bigger registers
Program counter
Points to the address of the next instruction is to be fetched
As each instruction is executed, the program counter is incremented to point to the address of
the next instruction is to be fetched
One more important register in the 8051 is the PC (Program Counter). The program counter points to
the address of next instruction to be fetched. As the CPU fetches the opcode from program ROM, the
program counter is incremented by 1 to point to the next instruction. The PC in the 8051 is 16 bit
register. This means that the 8051 can access program addresses 0000 to FFFFH, a total of 64K bytes
of code.
_________________________________________________________________________________
www.vectorindia.org 11
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Instruction decoder
Interprets the instruction fetched into the CPU
A CPU capable of understanding more instructions requires more transistors to design
_________________________________________________________________________________
www.vectorindia.org 12
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Types of Microcontrollers
Microcontrollers can be classified on the basis of internal bus width, architecture, memory and
instruction set. Figure 1.4 shows the various types of microcontrollers.
Examples
The 8- Bit Microcontrollers are Intel 8051 family and Motorola MC68HC11 family.
Examples
The 16-bit microcontrollers are Intel 8096 family and Motorola MC68HC12 and MC68332 families.
The performance and computing capability of 16 bit microcontrollers are enhanced with greater
precision as compared to the 8-bit microcontrollers.
Examples
The 32-bit microcontrollers are Intel 80960 family and Motorola M683xx and Intel/Atmel 251
family. The performance and computing capability of 32 bit microcontrollers are enhanced with
greater precision as compared to the 16-bit microcontrollers.
_________________________________________________________________________________
www.vectorindia.org 13
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Von-Neuman Architecture
Microcontrollers based on the Von-Neuman architecture have a single data bus that is used to fetch
both instructions and data. Program instructions and data are stored in a common main memory.
When such a controller addresses main memory, it first fetches an instruction, and then it fetches the
data to support the instruction. The two separate fetches slows up the controller’s operation. The
Von-Neuman architecture’s main advantage is that it simplifies the microcontroller design because
only one memory is accessed. In microcontrollers, the contents of RAM can be used for data storage
and program instruction storage.
Example: Motorola 68HC11 microcontroller
_________________________________________________________________________________
www.vectorindia.org 14
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Harvard Architecture
Microcontrollers based on the Harvard Architecture have separate data bus and an instruction bus.
This allows execution to occur in parallel. As an instruction is being “pre-fetched”, the current
instruction is executing on the data bus. Once the current instruction is complete, the next instruction
is ready to go. This pre-fetch theoretically allows for much faster execution than Von-Neuman
architecture, on the expense of complexity. The Harvard Architecture executes the instructions in
fewer instruction cycles than the Von-Neuman architecture.
Example: Intel MCS-51 family (8051), PIC microcontrollers
The typical CISC microcontroller has well over 80 instructions, many of them very powerful and
very specialized for specific control tasks. It is quite common for the instructions to all behave quite
differently. Some might only operate on certain address spaces or registers, and others might only
recognize certain addressing modes.
The advantages of the CISC architecture are that many of the instructions are macro like, allowing
the programmer to use one instruction in place of many simpler instructions.
Eg: Intel 8096 and 8051 family
_________________________________________________________________________________
www.vectorindia.org 15
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Applications
Home monitoring System
Automotive Appliances
Microwave Oven
Refrigerators
Television
VCRs
Stereos
Automobiles
Engine Control
Diagnostics
Climate Control
Environmental Control
Green House
Factory
Home
_________________________________________________________________________________
www.vectorindia.org 16
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Instrumentation
Aerospace
Robotics
Data logging (from Sensors like Temperature, Humidity etc...)
Micro-coded processor
It’s a processor within a processor, or a state machine that executes each different instruction as the
address to a subroutine of instructions.
Hardwired processor
A processor which uses the bit pattern of the instruction to access specific logic gates (unique to the
instruction), which are executed as a combinatorial circuit to carry out the instruction
_________________________________________________________________________________
www.vectorindia.org 17
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
8051 Microcontroller
Features
The main features of 8051 microcontroller are
RAM – 128 Bytes (Data memory)
ROM – 4Kbytes (ROM signify the on – chip program space)
8-bit data bus – It can access 8 bits of data in one operation
16-bit address bus – It can access 216 memory locations for dual purpose – 64 KB (65536
locations) each of RAM and ROM
Serial Port – Using UART makes it simpler to interface for serial communication.
Two 16 bit Counter/Timers
Input/output Pins – 4 Ports of 8 bits each on a single chip.
6 Interrupt Sources
8 bit ALU (Arithmetic Logic Unit), Accumulator and 8-bit Registers; hence it is an 8-bit
microcontroller
Harvard Memory and CISC Architecture
8051 can execute 1 million one-cycle instructions per second with a clock frequency of
12MHz.
8051 consists of 16-bit program counter and data pointer
8051 also consists of 32 general purpose registers each of 8 bits
The 8051 contains a micro coded processor that is in contrast to other microcontroller that uses a
hardwired one.
_________________________________________________________________________________
www.vectorindia.org 18
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 19
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 20
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 21
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Crystal Circuit
The 8051 has an on-chip oscillator but requires an external clock to run it
A quartz crystal oscillator is connected to inputs XTAL1 (pin19) and XTAL2 (pin18)
The quartz crystal oscillator also needs two capacitors of 30 pF value
RESET (RST)
RESET pin is an input and is active high (normally low)
Upon applying a high pulse to this pin, the microcontroller will reset and terminate all
activities
This is often referred to as a power-on reset
Activating a power-on reset will cause all values in the registers to be lost
In order for the RESET input to be effective, it must have a minimum duration of 2 machine cycles
In other words, the high pulse must be high for a minimum of 2 machine cycles before it is
allowed to go low
_________________________________________________________________________________
www.vectorindia.org 22
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
EA bar
EA, “external access’’, is an input pin and must be connected to Vcc or GND
The 8051 family members all come with on-chip ROM to store programs
-EA pin is connected to Vcc
The 8031 and 8032 family members do no have on-chip ROM, so code is stored on an
external ROM and is fetched by 8031/32
-EA pin must be connected to GND to indicate that the code is stored externally
The following two pins are used mainly in 8031-based systems
_________________________________________________________________________________
www.vectorindia.org 23
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Lower 128 bytes of RAM address range is 00H to 7FH.How can manufacturer divided these 128
bytes as given in below table:
_________________________________________________________________________________
www.vectorindia.org 24
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
The upper RAM area and the SFR (Special Function Register) area share the same address locations.
They are accessed through different addressing modes. Any location in the general-purpose RAM
can be accessed freely using the direct or indirect addressing modes.
_________________________________________________________________________________
www.vectorindia.org 25
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Bank 1 uses the same ram space as the stack. Register bank 0 is the default when the 8051 is
powered up. We can switch to other banks by use of the PSW (Program status word) register. PSW is
one of the SFR (Special Function Register) and also this one is bit addressable register. So, we can
access bit addressable instructions SETB and CLR. In this register PSW.3 and PSW.4 bits are used
to select the desired register bank as shown in below table.
If we are using CLR PSW.x instruction then it makes zero value in that particular bit, and if we are
using SETB PSW.x instruction then one(1) value passes in that particular bit. Where ‘x’ represents
either 3 (or) 4
_________________________________________________________________________________
www.vectorindia.org 26
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 27
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 28
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 29
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Program Memory
_________________________________________________________________________________
www.vectorindia.org 30
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Assembly Language
An assembly language is a low-level programming language for a computer, microcontroller, or
other programmable device, in which each statement corresponds to a single machine code
instruction. Each assembly language is specific to particular computer architecture, in contrast to
most high-level programming languages, which are generally portable across multiple systems.
An assembler creates object code by translating assembly instruction mnemonics into opcodes, and
by resolving symbolic names for memory locations and other entities.
Assembly language uses a mnemonic to represent each low-level machine operation or opcode.
Some opcodes require one or more operands as part of the instruction, and most assemblers can take
labels and symbols as operands to represent addresses and constants, instead of hard coding them
into the program.
Syntax
LABEL: MNEMONIC OPERANDS ; COMMENTS
Example: MOV destination, source; copy source to dest.
The instruction tells the CPU to move (in reality, COPY) the source operand to the
destination operand
Register are used to store information temporarily, while the information could be
a byte of data to be processed, or
an address pointing to the data to be fetched
The vast majority of 8051 register are 8-bit registers
There is only one data type, 8 bits
_________________________________________________________________________________
www.vectorindia.org 31
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
1) First we use an editor to type a program, many excellent editors or word processors are available
that can be used to create and/or edit the program
Notice that the editor must be able to produce an ASCII file
For many assemblers, the file names follow the usual DOS conventions, but the source file
has the extension “asm“ or “src”, depending on which assembly you are using
_________________________________________________________________________________
www.vectorindia.org 32
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
2) The “asm” source file containing the program code created in step 1 is fed to an 8051 assembler
The assembler converts the instructions into machine code
The assembler will produce an object file and a list file
The extension for the object file is “obj” while the extension for the list file is “lst”
3) Assembler require a third step called linking
The linker program takes one or more object code files and produce an absolute object file
with the extension “abs”
This abs file is used by 8051 trainers that have a monitor program
4) Next the “abs” file is fed into a program called “OH” (object to hex converter) which creates a file
with extension “hex” that is ready to burn into ROM
This program comes with all 8051 assemblers
Recent Windows-based assemblers combine step 2 through 4 into one step
Addressing Modes
It is a way to address an operand i.e., an "addressing mode" refers to how you are addressing a given
memory location. Total 5 types of addressing modes are available in 8051 those are given in below.
_________________________________________________________________________________
www.vectorindia.org 33
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Examples
MOV A, #0 ; put 0 in the accumulator
A = 00000000
MOV R0, #0x11 ; put 11hex in the R0 (BANK 0)
R0 = 00010001
MOV @R0, #11 ; put 11 decimal in to internal RAM with address contained in R0
11h= 00001011
MOV DPTR, #77h ; put 77 hex in DPTR
DPTR=77h
_________________________________________________________________________________
www.vectorindia.org 35
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Examples
MOV R0, #34h ; put 34h value in R0 register
MOV A, R0 ; put contents of R0 in to “A” register
_________________________________________________________________________________
www.vectorindia.org 36
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Examples
MOV DPTR, #4000h ; DPTR 4000h
MOV A, #5h ; A 5h
MOVX @DPTR, A ; M [4000] A
MOVX A, @DPTR ; A M [4000]
Note that 9000 is an address in external memory and ‘A’ is an accumulator register.
Instruction Set
Instruction set is a collection of Instructions are used in 8051 to perform specific applications. Total
4 types of Instruction Sets are available in 8051 those are discussed in below.
_________________________________________________________________________________
www.vectorindia.org 37
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
In these two operands one is source operand and another one is destination operand. In this
instruction set mnemonic is “MOV”, operands are either constant data, registers, addresses or
indirect registers those examples are given below.
Syntax: MOV Destination, Source ; destination source
According to above syntax whatever the data in source operand that is moved on to the destination
operand
Examples
MOV a, #data ; move data to accumulator
MOV addr, a ; move accumulator to addr
MOV Rn, addr ; move data of that address to register of current bank (Where n=0-7)
MOV addr1, addr2; move data in that addr to internal RAM
MOV @Ri,#data; move data to internal RAM with address contained in Ri (where i=0/1)
MOV DPTR, #data (16-bit); move 16-bit data into data pointer
Above examples are transfers the data from source to destination and those operands are related to
internal ram section only. Above examples and remaining examples of data transfer instruction set
explanation as given in below (In Addressing modes Examples).
A and B are Registers
A, B registers are used for arithmetic instructions. They can be accessed by direct mode as special
function registers
B – Address 0F0h
A – Address 0E0h - use “ACC” for direct mode
Stack-oriented data transfer – another form of register indirect addressing, but using SP
Examples
MOV SP, #0x40 ; Initialize SP
PUSH 0x55 ; SP SP+1, M [SP] M [55] i.e., M [41] M [55]
POP B ; B M [55], SP SP-1
_________________________________________________________________________________
www.vectorindia.org 38
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
The stack is a section of RAM used by the CPU to store information temporarily
This information could be data or an address
The register used to access the stack is called the SP (stack pointer) register
The stack pointer in the 8051 is only 8 bit wide, which means that it can take value of 00 to
FFH
When the 8051 is powered up, the SP register contains value 07
RAM location 08 is the first location begin used for the stack by the 8051
The storing of a CPU register in the stack is called a PUSH
SP is pointing to the last used location of the stack
As we push data onto the stack, the SP is incremented by one
This is different from many microprocessors
Loading the contents of the stack back into a CPU register is called a POP
With every pop, the top byte of the stack is copied to the register specified by the instruction
and the stack pointer is decremented once
Note: can only specify RAM or SFRs (direct mode) to push or pop. Therefore, to push/pop the
accumulator, must use acc, not a.
Possibilities
PUSH acc
pop
push
Stack
Stack pointer
_________________________________________________________________________________
www.vectorindia.org 39
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Exchange Instructions
two way data transfer i.e., move data in two directions
All exchanges are internal to 8051
All exchange instructions use “Accumulator”
When using XCHD, the upper nibbles are not exchanged
Possibilities
XCH A, Rn --> n=0-7
XCH A, addr
XCH A, @Ri --> i=0(or)1
XCHD A, @Ri
Examples
XCH A, 0x30 ; A M [30]
XCH A, R0 ; A R0
XCH A, @R0 ; A M [R0]
XCHD A, @R0 ; exchange lower nibbles of ‘A' register and M [R0] register.
Data Processing Instructions
Arithmetic Instruction Set
Logical Instruction Set
Add
Subtract
Increment
Decrement
Multiply
Division
Decimal adjust
_________________________________________________________________________________
www.vectorindia.org 40
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Mnemonic Description
ADD A, #data add A to byte, put result in A
ADDC A, addr add A, data in address with carry
SUBB A, addr subtract A, data in address with borrow
INC A increments the data by 1 in “A” register
INC addr increment data by 1 in memory(address)
INC DPTR increment data by 1 in data pointer
DEC A decrement the data by 1 in accumulator
DEC addr decrement the data by 1 in addr
MUL AB multiply accumulator with b register
DIV AB divide accumulator by b register
DA A decimal adjust the accumulator
Options
ADD A, #data (8bit)
ADDC A, Rn
SUBB A, direct_addr
A, @Ri
Examples
ADD A, byte ; A A + byte
ADDC A, byte ; A A + byte + C
These instructions affect 3 bits in PSW:
C = 1 if result of add is greater than FF
AC = 1 if there is a carry out of bit 3
OV = 1 if there is a carry out of bit 7, but not from bit 6, or vice versa.
_________________________________________________________________________________
www.vectorindia.org 41
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Q) What is the value of the C, AC and an OV flags after the second Instruction is executed for
below example?
MOV A, #0x3F
ADD A, #0xD3
Ans: 0011 1111 C=1
1101 0011 AC = 1
0001 0010 OV = 0
Subtract
SUBB A, #data subtract with borrow
Example:
SUBB A, #0x4F ; A A – 4F – C
Notice that there is no subtraction WITHOUT borrow. Therefore, if a subtraction without
borrow is desired, it is necessary to clear the C flag.
_________________________________________________________________________________
www.vectorindia.org 42
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Note: When we are getting more than 8 bits (1 byte), then B gets the HIGH byte, A gets the LOW
byte
Division
DIV AB ; divide A by B
A Quotient (A/B), B Remainder (A/B)
OV - used to indicate a divide by zero condition.
C – Set to zero
Decimal Adjust
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. If the carry bit
is set or if the value of bits 0-3 exceeds 9, 0x06 is added to the accumulator. If the carry bit was set
when the instruction begins (or) if 0x06 was added to the accumulator in the first step, 0x60 is added
to the accumulator. The Carry bit (C) is set if the resulting value is greater than 0x99, otherwise it is
cleared.
_________________________________________________________________________________
www.vectorindia.org 43
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 44
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
CPL
It complements the value in a register i.e., when this instruction is executed it makes zeros to
ones and ones to zeros.
We are using only one operand in this instruction i.e., Accumulator. This register only acts as
both source and destination operand final result is stored in ‘a’ register itself.
Syntax: CPL A
CLR
Set all bits to 0
Syntax: CLR A
CLR bit_addr
Rotate
Rotate instructions operate only on a. We are using only one operand in below instructions i.e.,
Accumulator. This register only acts as both source and destination operand final result is stored in
‘a’ register itself.
_________________________________________________________________________________
www.vectorindia.org 45
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Example
MOV A, #0xF0 ; A 11110000
RL A ; A 11100001
RRC RLC
Example
MOV A, #0A9h ; A A9
ADD A, #14h ; A BD (10111101), C0
RRC A ; A 01011110, C1
Swap
This instruction swaps the data in A register i.e., it changes lower nibbles to higher nibbles and
higher nibbles to lower nibbles
Syntax: SWAP A
Example:
MOV A, #72h ; A 72h
SWAP A ; A 27h
_________________________________________________________________________________
www.vectorindia.org 46
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Shift/Multiply Example
Program segment to multiply by 2 and add 1
CLR C
RL A ; multiply by 2
INC A ; and add one
Unconditional Jumps
• SJMP <rel addr> - Sort jump, relative address is 8-bit 2’s complement number, so jump
can be up to 127 locations forward, or 128 locations back.
• LJMP <address 16> - Long jump
• AJMP <address 11> - Absolute jump to anywhere within 2K block of program memory
• JMP @A + DPTR - Long indexed jump
Infinite Loops
Example
Start: MOV C, P3.7
MOV P1.6, C
SJMP Start
Microcontroller application programs are almost always infinite loops!
Re-locatable Code
Start: MOV C, P1.6
MOV P3.7, C
SJMP Start
Conditional Jump
These instructions cause a jump to occur only if a condition is true. Otherwise, program execution
continues with the next instruction.
loop: MOV A, P1
JZ loop ; if a=0, go to loop, else go to next instruction
MOV B, A
Syntax
Mnemonic Description
JZ <rel addr> Jump if a = 0
JNZ <rel addr> Jump if a != 0
JC <rel addr> Jump if C = 1
_________________________________________________________________________________
www.vectorindia.org 48
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Example: If C is 1 led should be ON else led should be off i.e., when C is zero by using conditional
jump instruction
JZ led_off
SETB C
MOV P1.6, C
SJMP skipover
led_off: CLR C
MOV P1.6, C
skipover: MOV A, P0
_________________________________________________________________________________
www.vectorindia.org 49
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Examples
1) Increment a value up to 4 2) Decrement R0 value from 4 to 0 and increment A value
Return (RET)
Return instruction pops PC from stack to get address to jump to
Syntax
RET ; PC stack
Initializing Stack Pointer
The Stack Pointer (SP) is initialized to 0x07. (Same address as R7)
When using subroutines, the stack will be used to store the PC, so it is very important to
initialize the stack pointer. Location 2F is often used.
MOV SP, #0x2F
Sub Routines
Subroutines allow us to have "structured" assembly language programs.
This is useful for breaking a large design into manageable parts.
It saves code space when subroutines can be called many times in the same program.
_________________________________________________________________________________
www.vectorindia.org 50
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
• Assembler Directives
– Instructions for the ASSEMBLER
– NOT 8051 instructions
– Give direction to the assembler
Note: From above assembler directives few are discussed in below with examples
_________________________________________________________________________________
www.vectorindia.org 51
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
DATA
Used to define a name for memory locations
Syntax
Symbol DATA data_address
Example
SP DATA 0x81 ; special function registers
MY_VAL DATA 0x44 ; RAM location
_________________________________________________________________________________
www.vectorindia.org 52
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
data_address
is a data memory address in the range 0 to 127
Or a special function registers (SFRs) address in the range 128 - 255.
BIT
Used to define a name for memory locations of particular bits
Syntax
Symbol BIT bit_address
Example: B0 BIT 20H.0
bit_address:
Is the address of a bit in internal data memory in the area 20H-2FH
Or a bit address of an 8051 bit-addressable SFR.
_________________________________________________________________________________
www.vectorindia.org 53
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
MACRO
Macro’s in A51:
A macro is a name that you assign to one or more assembly statements.
The Ax51 assembler will replace the macro name with the text specified in the macro
definition.
Usage
Symbol MACRO no_arg ; begin macro definition
Usage
Symbol MACRO args_up_to_16 ; begin macro definition
CSEG AT 0
REGBANK0 ; USING MACRO
MOV R0, #1
REGBANK1 ; USING MACRO
MOV R0, #2
SUM 1, 2 ; USING MACR0
END
_________________________________________________________________________________
www.vectorindia.org 55
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
File Extensions
Machine cycle
To execute an instruction–the processor must these four steps refer to Machine Cycle.
1. Fetch the instruction from memory
2. Decode the instruction
3. Execute the instruction
4. Store the result back in the memory.
Generally one machine cycle = X clock cycles (_X_ depends on the particular instruction
being executed). For short clock cycle less time it takes to complete one machine cycle, so
instructions are executed faster.
Fetching and executing an instruction
Fetching involves the following steps
Contents of PC are placed on address bus.
READ signal is activated.
Data (instruction opcode) are read from RAM and placed on data bus.
Opcode is latched into the CPU’s internal instruction register.
PC is incremented to prepare for the next fetch from memory.
_________________________________________________________________________________
www.vectorindia.org 56
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
While execution involves decoding the opcode and generating control signals to gate internal
registers in and out of the ALU and to signal the ALU to perform the specified operation.
Instruction/machine cycle - is the time period (measured by the number of oscillator clock
cycles) during which a CPU processes a machine language instruction from its memory.
T= (1x12)/12MHz =>1microsecond
So, if you are taking 12 MHz frequency time period is 1 microsecond for 1 machine cycle.
2) By using above formula calculate time for 1machine cycle by using 11.0592 MHz frequency
T= (1x12)/11.0592MHz =>1.085microsecond
So, if you are taking 12 MHz frequency time period is 1.085 microsecond for 1 machine cycle.
_________________________________________________________________________________
www.vectorindia.org 57
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
8051 instructions having varying machine cycles. So, apply these values based on instructions and
calculate Time Period i.e., delay. This delay we are using in peripheral programs like LED, 7-
Segment etc… for knowing the status in between two operations Examples are given below for 1 ms
time delay.
Delay
/*Write an ALP to generate 1ms time delay by using 12 MHz crystal frequency*/
MOV R7, #250 ; for MOV instruction it takes 1 machine cycle i.e., ;
; 1m=1microsecond
l1:
DJNZ R7, l1 ; for branch instruction it takes 2 machine cycles i.e.,
; 2m.c=2microseconds it checks R7 value it rotates there
; up to R7 gets zero value it rotates total 250 times
; i.e., 250*2=500machine cycles=500 Microseconds
MOV R6, #249 ; for MOV instruction it takes 1 machine cycle i.e.,
; 1m.c=1microsecond
l2:
DJNZ R6, l2 ; for branch instruction it takes 2 machine cycles
; i.e., 2m.c=2microseconds it checks R7 value it rotates
; There up to R7 gets zero value it rotates total 249
; Times i.e., 249*2=498machine cycles=500 Microseconds
END ; at the end calculate total machine cycles
Output: 1+500+1+498=1000
_________________________________________________________________________________
www.vectorindia.org 58
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
/*Write an ALP to generate 1ms time delay by using 11.0592 MHz crystal frequency*/
CSEG AT 0 ; cycles
Output:
1.085+ (225*2.17) +1.085+ (225*2.17) +1.085+ (9*2.17) =999.285 approx=1millisec
/*Write an ALP to generate 10ms time delay by using 12 MHz crystal frequency*/
CSEG AT 0
ACALL DELAY10MS ; including ACALL
SJMP $ ; It rotates there it self
DELAY1MS: ; cycles
MOV R7, #250 ; 1
L1: DJNZ R7, L1 ; 2*250=500
MOV R6, #247 ; 1
L2: DJNZ R6, L2 ; 2*247=494
RET ; 2
DELAY10MS: ; Cycles
MOV R5, #09 ; 1
L3: ACALL DELAY1MS ; 9*1ms=9ms
DJNZ R5, L3 ; 9*2us=18us
MOV R7, #250 ; 1
L4: DJNZ R7, L4 ; 2*250=500
MOV R5, #237 ; 1
L5: DJNZ R5, L5 ; 2*237=474
_________________________________________________________________________________
www.vectorindia.org 59
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
NOP ; 1
RET ; 2
END
/*OUTPUT:
TOTAL ; 10MILLI SECONDS*/
/*Write an ALP to generate 100ms time delay by using 1ms & 10ms delays frequency is 12 MHz*/
CSEG AT 0
ACALL DELAY100MS ; Including ACALL
SJMP $ ; It rotates there it self
DELAY1MS: ; cycles
MOV R7, #250 ; 1
L1: DJNZ R7, L1 ; 2*250=500
MOV R6, #247 ; 1
L2: DJNZ R6, L2 ; 2*247=494
RET ; 2
DELAY10MS: ; Cycles
MOV R5, #09 ; 1
L3: ACALL DELAY1MS ; 9*1ms=9ms
DJNZ R5, L3 ; 9*2us=18us
MOV R7, #250 ; 1
L4: DJNZ R7, L4 ; 2*250=500
MOV R5, #237 ; 1
L5: DJNZ R5, L5 ; 2*237=474
NOP ; 1
RET ; 2
DELAY100MS: ; Cycles
MOV R0, #09 ; 1
L6: ACALL DELAY10MS ; 9*10ms=90ms
DJNZ R0, L6 ; 9*2us=18us
MOV R5, #09 ; 1
L7: ACALL DELAY1MS ; 9*1ms=9ms
_________________________________________________________________________________
www.vectorindia.org 60
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
All the ports upon RESET are configured as input, ready to be used as input ports
To reconfigure it as an input, “1” value must be sent to the port
To use any of these ports as an input port, it must be programmed
When the first 0 is written to a port, it becomes an output
Port 0
It can be used for input or output; each pin must be connected externally to a 10K ohm pull-up
resistor
This is due to the fact that P0 is an open drain, unlike P1, P2, and P3
Open drain is a term used for MOS chips in the same way that open collector is used for TTL
chips
Dual Role of Port 0
Port 0 is also designated as AD0-AD7, allowing it to be used for both address and data
When connecting an 8051/31 to an external memory, port 0 provides both address and data
_________________________________________________________________________________
www.vectorindia.org 61
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
DELAY1MS: ; cycles
MOV R7, #250 ; 1
L1: DJNZ R7, L1 ; 2*250=500
MOV R6, #247 ; 1
L2: DJNZ R6, L2 ; 2*247=494
RET ; 2
DELAY10MS: ; Cycles
MOV R5, #09 ; 1
L3: ACALL DELAY1MS ; 9*1ms=9ms
DJNZ R5, L3 ; 9*2us=18us
MOV R7, #250 ; 1
L4: DJNZ R7, L4 ; 2*250=500
MOV R5, #237 ; 1
L5: DJNZ R5, L5 ; 2*237=474
NOP ; 1
RET ; 2
DELAY100MS: ; Cycles
MOV R0, #09 ; 1
L6: ACALL DELAY10MS ; 9*10ms=90ms
DJNZ R0, L6 ; 9*2us=18us
MOV R5, #09 ; 1
L7: ACALL DELAY1MS ; 9*1ms=9ms
DJNZ R5, L7 ; 9*2=18us
MOV R7, #250 ; 1
L8: DJNZ R7, L8 ; 2*250=500
MOV R5, #228 ; 1
L9: DJNZ R5, L9 ; 2*228=456
RET
END
_________________________________________________________________________________
www.vectorindia.org 62
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
/* The following code will continuously send out to port 0 the alternating value 55H and AAH */
$include(delay.asm)
CSEG AT 0 ; it starts from 0th memory location
BACK: MOV A, #55H
MOV P0, A
ACALL DELAY100MS
MOV A, #0AAH
MOV P0, A
ACALL DELAY100MS
SJMP BACK
END ; it ends the program
/* Port 0 is configured first as an input port by writing 1s to it, and then data is received from that
port and sent to P1 */
Port 1
Port 1 can be used as input or output
In contrast to port 0, this port does not need any pull-up resistors since it already has pull-up
resistors internally
Upon reset, port 1 is configured as an input port
_________________________________________________________________________________
www.vectorindia.org 63
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
/* The following code will continuously send out to port 0 the alternating value 55H and AAH */
/* Port 1 is configured first as an input port by writing 1s to it, then data is received from that port
and saved in R7 and R5 */
$include(delay.asm)
CSEG AT 0 ; it starts from 0th memory location
MOV A, #0FFH ; A=FF hex
MOV P1, A ; make P1 an input port by writing it all 1s
MOV A, P1 ; get data from P1
MOV R7, A ; save it to in register R7
ACALL DELAY100MS ; wait
MOV A, P1 ; another data from P1
MOV R5, A ; save it to in register R5
END ; it ends the program
Port 2
Port 2 can be used as input or output
Just like P1, port 2 does not need any pull up resistors since it already has pull-up resistors
internally
Upon reset, port 2 is configured as an input port
_________________________________________________________________________________
www.vectorindia.org 64
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
$include(delay.asm)
CSEG AT 0 ; it starts from 0th memory location
BACK: CPL P1.2 ; complement P1.2
ACALL DELAY10MS ; wait up to 10ms
SJMP BACK ; go to back label
/*another variation of the above program*/
AGAIN: SETB P1.2 ; set only P1.2
ACALL DELAY10MS ; wait up to 10ms
CLR P1.2 ; clear only P1.2
ACALL DELAY10MS ; wait up to 10ms
SJMP AGAIN ; go to AGAIN label
END ; it ends the program
LED:
If any LED wants to glow by using microcontroller we have to know about Active Low LED and
Active High LED. Those are discussed in below
First you can connect LED with the Port line. The activation level is selectable as either 1 or 0. If you
want to use activation level 1, then we have to pass high value from microcontroller to the led then
the connected LED glows at the port line for the active high level condition. Otherwise, LED glows
at the low level signal when you are connected LED as an Active Low condition.
The actual real time circuits that represent the above choice of point LED interfacing is given here
for your reference.
_________________________________________________________________________________
www.vectorindia.org 66
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Note: For driving LEDs, 10K resistor is not required. But when you drive relays, the pull up 10K
resistor is required because the output current sourcing capacity of any port line varies between 60
and 100 micro A. This small current is insufficient to drive the base of high current transistor.
Note: If you want to know about LED refer Diodes topic in previous chapter.
/*Flash an LED connected to any of the port pin using logical instruction set at the rate of 10ms*/
FILE NAME: LED.ASM
LED EQU P1.0 ; Port 1.0 pin is assigned to variable name of LED
CSEG AT 0 ; starts from 0th memory location
AGAIN:
CLR LED ; LED gets zero value P1.0 0
ACALL DELAY100MS ; wait up to 100milliseconds
SETB LED ; LED gets one value P1.0 1
ACALL DELAY100MS ; wait up to 100milliseconds
SJMP AGAIN ; it jumps to label name of AGAIN
DELAY10MS: ; Cycles
MOV R5, #09 ; 1
L3: ACALL DELAY1MS ; 9*1ms=9ms
DJNZ R5, L3 ; 9*2us=18us
MOV R7, #250 ; 1
_________________________________________________________________________________
www.vectorindia.org 67
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
DELAY100MS: ; Cycles
MOV R0, #09 ; 1
L6: ACALL DELAY10MS ; 9*10ms=90ms
DJNZ R0, L6 ; 9*2us=18us
MOV R5, #09 ; 1
L7: ACALL DELAY1MS ; 9*1ms=9ms
DJNZ R5, L7 ; 9*2=18us
MOV R7, #250 ; 1
L8: DJNZ R7, L8 ; 2*250=500
MOV R5, #228 ; 1
L9: DJNZ R5, L9 ; 2*228=456
RET
END
Solution 2: Here Delay definitions (Subroutines) in DELAY.ASM file, that file you can include in
this main file with the help of $include
/*Note: If we want to maintain any file as a sub header file don’t include CSEG
and END assembler directives*/
$include (DELAY.ASM)
LED EQU P1.0 ; Port 1.0 pin is assigned to variable name of LED
CSEG AT 0 ; starts from 0th memory location (Assembler Directive)
AGAIN:
CLR LED ; LED gets zero value P1.0 0
ACALL DELAY100MS ; wait up to 100milliseconds
SETB LED ; LED gets one value P1.0 1
ACALL DELAY100MS ; wait up to 100milliseconds
SJMP AGAIN ; it jumps to label name of AGAIN
Switch
When you select the Momentary switch interface, a momentary switch can be connected to the I/O
lines of the controller. The activating level for the individual switches can be set either as 1 or 0.
Activating level means the level when the switch is in the pressed condition.
Example
If level 1 is selected as activation level for a particular switch, then during normal (unpressed)
condition the port line (connected to that switch) assumes a 0 level.
When the same switch is in the pressed condition, level 1 will be fed into the port line.
_________________________________________________________________________________
www.vectorindia.org 69
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
If level 0 is selected as activation level for a particular switch, then during normal (unpressed)
condition the port line (connected to that switch) assumes a 1 level.
When the same switch is in the pressed condition, level 0 will be fed into the port line.
In the Toggle switch interface, a toggle switch can be connected with any on of the port lines of the
controller.
/* A momentary switch (SW) is connected to P2.0 and 8 LEDs are connected to P1 now flash the
LEDs when we pressed the switch using complement logic*/
_________________________________________________________________________________
www.vectorindia.org 70
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
7-SEG Display is available in two types – one is Common anode and second one is Common
cathode, but common anode display are most suitable for interfacing with 8051 since 8051 port pins
can sink current better than sourcing it.
_________________________________________________________________________________
www.vectorindia.org 71
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
In the seven segment displays, the port lines are directly connected to the segments of the display and
segments glow according to the display data available at the port lines and also the display type,
common anode or common cathode. In the external multiplexer configuration, a multiplexing
device, like 74LS139 (2 to 4), 74LS138 (3 to 8) or 74LS154 (4 to 16) is connected between the port
lines and the digit select control lines of the display. Some of the real time circuit examples to
connect the seven segment displays are given here for your reference.
_________________________________________________________________________________
www.vectorindia.org 72
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
The circuit shown here is meant for the common anode display with the seven segment inputs. In this
configuration, the port lines are connected to the segments of the display directly or through buffers.
When using this configuration, you can connect a maximum of 4 digits of displays with the
controllers having 32 I/O lines.
For the common cathode type displays, you can’t connect the port lines directly to the segment lines
as you have seen above because the source current of any port line is about 60microA.
You can use a buffer between the port lines and the segment lines of the display as shown here.
_________________________________________________________________________________
www.vectorindia.org 73
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
/* Write an ALP to display 0-9 numbers on 7-Segment Display (Common Cathode) by using delay
header file*/
FILE NAME: SEG. ASM
$include (DELAY.ASM)
CSEG AT 0100H
LUT: DB 0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90
_________________________________________________________________________________
www.vectorindia.org 74
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
CJNE A, #09, AGAIN; if “A” register value is not equal to “09” it jumps
; to label Else it executes next instruction
SJMP $ ; It rotates here it self
Note: “DELAY.ASM” sub header file is mentioned in above refer that file
Embedded C
Introduction
It is not part of the C language. But, it is a C language extension that is the subject of a technical
report by the ISO working group named "Extensions for the Programming Language C to
Support Embedded Processors”. It aims to provide portability and access to common performance-
increasing features of processors used in the domain of DSP and embedded processing. The
Embedded C specification for fixed-point, named address spaces, and registers gives the programmer
direct access to features in the target processor, thereby significantly improving the performance of
applications. The hardware I/O extension is a portability feature of Embedded C. Its goal is to allow
easy porting of device-driver code between systems.
KEIL software is an IDE EMBEDDED C
(Using C51 cross compiler)
Language Extensions
C51 provides a number of extensions of ANSI standard C. Most of these provide direct support for
elements of the 8051 architecture.
_________________________________________________________________________________
www.vectorindia.org 75
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Key Words
To facilitate many of the features of the 8051, C51 adds a number of new keywords to the scope of
the language. The following is the list of keywords
Memory Areas
The 8051 architecture supports several physically separate memory areas or memory spaces for
program and data. Each memory area offers certain advantages and disadvantages. Those are
discussed in below.
Program Memory
Program memory may be accessed using the code memory type specifier in the C51 compiler.
The data memory specifier always refers to the first 128 bytes of internal data memory.
These variables are accessed using direct addressing.
The idata memory specifier refers to all 256 bytes for (89s52) and 128 bytes for (8051) of
internal data memory; however, this memory type specifier code is generated by indirect
addressing which is slower than direct addressing.
_________________________________________________________________________________
www.vectorindia.org 76
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
The bdata memory specifier refers to the 16 bytes of bit-addressable memory in the internal
data memory i.e., RAM area (20h to 2Fh). This memory type specifier allows you to declare
data types that can also be accessed at the bit level.
Memory Models
The memory models determine which default memory type to use for function arguments, automatic
variables and declarations with no explicit memory type specifier.
Small Model
In this model, by default all variables reside in the internal data memory.
Variable access is very efficient.
However the stack should fit into the internal RAM
Compact Model
In this case, all variables reside in one page of external data memory.
This memory model can accommodate a maximum of 256 bytes of variables.
In this model, C51 accesses the external memory with instructions that utilize the @R0 and
@R1 operands.
Large Model
In this model, all variables reside in the external data memory up to 64k bytes
The data pointer is used for addressing.
_________________________________________________________________________________
www.vectorindia.org 77
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Examples
char data var1;
char code text[] = "ENTER PARAMETER:";
unsigned long xdata array [100];
float idata x, y, z;
unsigned int pdata dimension;
unsigned char xdata vector [10][4][4];
char bdata flags;
Data Types
Data type bits bytes range
bit 1 0 or 1
sbit 1 0 or 1
sfr 8 1 0 to 255
sfr16 16 2 0 to 65535
Example 1
int bdata ibase; /* Bit-addressable int */
char bdata bary [4]; /* Bit-addressable array */
sbit mybit0 = ibase ^ 0; /* bit 0 of ibase */
sbit mybit15 = ibase ^ 15; /* bit 15 of ibase */
sbit Ary07 = bary[0] ^ 7; /* bit 7 of bary[0] */
sbit Ary37 = bary[3] ^ 7; /* bit 7 of bary[3] */
main()
{
Ary37 = 1; /* clear bit 7 in bary[3] */
bary[3] = 'a'; /* Byte addressing */
ibase = -1; /* Word addressing */
mybit15 = 1; /* set bit 15 in ibase */
}
NOTE: You may not specify bit variables for the bit positions of a float.
_________________________________________________________________________________
www.vectorindia.org 79
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Access to 16-bit SFRs is possible only when the low byte immediately precedes the high byte. The
low byte is used as the address in the sfr16 declaration.
sfr16 DPTR = 0x82; /* DPTR : DPL 82h, DPH 83h */
For 8052
sfr16 T2 = 0xCC; /* Timer 2: T2L 0CCh, T2H 0CDh */
sfr16 RCAP2 = 0xCA; /* RCAP2L 0CAh, RCAP2H 0CBh */
With typical 8051 applications, it is often necessary to access individual bits within an SFR. The C51
compiler makes this possible with the sbit data type which provides access to bit-addressable SFRs
and other bit-addressable objects.
sbit OV = 0xD0 ^ 2;
sbit CY = 0xD0 ^ 7;
sbit EA = 0xA8 ^ 7;
sbit OV = 0xD2;
sbit CY = 0xD7;
sbit EA = 0xAF;
_________________________________________________________________________________
www.vectorindia.org 80
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
The following example demonstrates how to locate several different variable types using the _at_
keyword.
Example
char xdata text[256] _at_ 0xE000; /* array at xdata 0xE000 */
int xdata i1 _at_ 0x8000; /* int at xdata 0x8000 */
main()
{
i1 = 0x1234;
text[0] = 'a';
}
Pointers
The C51 compiler provides two different types of pointers:
generic pointers
Memory-specific pointers
_________________________________________________________________________________
www.vectorindia.org 81
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Generic Pointers
Generic pointers are declared in the same fashion as standard C pointers.
Examples
char *s; /* string ptr */
int *numptr; /* int ptr */
long *state; /* Texas */
Generic pointers are always stored using three bytes. The first byte is the memory type, the
second is the high-order byte of the offset, and the third is the low-order byte of the offset.
Generic pointers may be used to access any variable regardless of its location in 8051
memory space.
Memory-specific Pointers
Memory-specific pointers always include a memory type specification in the pointer
declaration and always refer to a specific memory area.
Examples
char data *str; /* ptr to string in data */
int xdata *numtab; /* ptr to int(s) in xdata */
long code *powtab; /* ptr to long(s) in code */
Memory-specific pointers can be stored using only one byte (idata, data, bdata,
and pdata pointers) or two bytes (code and xdata pointers).
The code generated for a memory-specific pointer executes more quickly than the equivalent
code generated for a generic pointer. This is because the memory area is known at compile-
time rather than at run-time. The compiler can use this information to optimize memory
accesses. If execution speed is a priority, you should use memory-specific pointers instead of
generic pointers wherever possible.
Like generic pointers, you may specify the memory area in which a memory-specific pointer
is stored.
_________________________________________________________________________________
www.vectorindia.org 82
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Examples
char data * xdata str; /* ptr in xdata to data char */
int xdata * data numtab; /* ptr in data to xdata int */
long code * idata powtab; /* ptr in idata to code long */
Memory-specific pointers may be used to access variables in the declared 8051 memory area
only.
Memory-specific pointers provide the most efficient method of accessing data objects, but at
the cost of reduced flexibility.
Embedded C Programming
Time delay
There are two way s to create a time delay in 8051 C
Using the 8051 timer (we will discussed in timers topic)
Using a simple for loop
be mindful of three factors that can affect the accuracy of the delay
The 8051 design
– The number of machine cycle
– The number of clock periods per machine cycle
The crystal frequency connected to the X1 – X2 input pins Compiler choice
-- C compiler converts the C statements and functions to Assembly
Language instructions
-- Different compilers produce different code
/*Write an ECP (Embedded C Programming) to generate 1ms time delay by using 1ms delay
frequency is 12 MHz*/
_________________________________________________________________________________
www.vectorindia.org 83
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
}
}
/*Write an ECP (Embedded C Programming) to generate 10ms time delay by using 1ms delay
frequency is 12 MHz*/
}
}
_________________________________________________________________________________
www.vectorindia.org 84
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
/*Write an ECP (Embedded C Programming) to generate 100ms time delay by using 1ms & 10ms
delays frequency is 12 MHz*/
main()
{
delay(100); // function name is “delay” call this function 100
// times for 100 ms
while(1); // By using this loop it rotates there it self it
// never fails
}
}
}
Note: Like above programs you can generate any delay with the help of same function definition how
much you want to generate that value you can place in delay function calling. But, by using for loops
we are not getting exact delay it’s an approximate delay. If you want exact delay then you can use
timers.
_________________________________________________________________________________
www.vectorindia.org 85
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
LED
/*Write an ECP to Flash an LED connected to any of the port pin at the rate of 500ms (check at
Active Low LED circuit)
FILE NAME: LED.C
main()
{
while(1) // infinite loop never fails why because 1 is constant
// non-zero value it rotates infinitely
{
led=0; // led P1^0 0, i.e., led gets ON position
delay(500); // it is delay function calling i.e., it waits up to 500ms
led=1; // led P1^0 1, i.e., led gets OFF position
delay(500); // it is delay function calling i.e., it waits up to 500ms
}
}
/*DELAY function definition*/
void delay(unsigned int i)
{
unsigned char j;
for(;i>0;i--) // in above delay calling function having one
// value “i” variable assigned to that value
{
for(j=255;j>0;j--); //it rotates 255 times there it self
_________________________________________________________________________________
www.vectorindia.org 86
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Solution 2:
Here Delay definitions (Subroutines) in DELAY.H file, that file you can include in this main file
with the help of “#include”
File Name: delay.h (Sub Header File)
_________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 87
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
main()
{
while(1) // infinite loop never fails why because 1 is constant
// non-zero value it rotates infinitely
{
led=0; // led P1^0 0, i.e., led gets ON position
delay(500); // it is delay function calling i.e., it waits up to 500ms
led=1; // led P1^0 1, i.e., led gets OFF position
delay(500); // it is delay function calling i.e., it waits up to 500ms
}
}
Note: Open one file save that file with one name in that just we have to write function definition then
that one will be considering as a sub header file. Include that header file in your main file with as it
is what we saved with that file name. In sub header file we have to write function definitions only.
Active low, active high led circuits are explained in above.
SWITCH
/* Write an ECP a momentary switch (SW) is connected to P2.0 and 8 LEDs are connected to P1
now “ON” the LEDs when we pressed the switch and vice versa*/
_________________________________________________________________________________
www.vectorindia.org 88
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
7-SEGMENT
/* Write an ECP to display 0-9 numbers on Common Cathode 7-Segment Display by using delay
header file*/
main()
{
unsigned char i; //declare "i" variable
while(1) // infinite loop
{
for(i=0;i<=9;i++) //for getting 0-9 values use for loop up
// to 9 times
{
seg =a[i]; //assign array values to segment
delay (1000); //wait second
}
}
}
_________________________________________________________________________________
www.vectorindia.org 89
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
/* Write an ECP to display 0-99 numbers on multiplexed Common Cathode 7-Segment Display by
using delay header file*/
FILE NAME: SEGMUX. C
_________________________________________________________________________________
www.vectorindia.org 90
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Key Board
Before learning “Interfacing Matrix Keypad to Microcontroller” you should know how to interface a
switch to microcontroller.
Introduction
Keypads are a part of HMI or Human Machine Interface and play really important role in a small
embedded system where human interaction or human input is needed. Matrix keypads are well
known for their simple architecture and ease of interfacing with any microcontroller.
_________________________________________________________________________________
www.vectorindia.org 91
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Now our keypad is ready, all we have to do is connect the rows and columns to a port of
microcontroller and program the controller to read the input.
There are many methods depending on how you connect your keypad with your controller, but the
basic logic is same. We make the columns as i/p and we drive the rows making them o/p, this whole
procedure of reading the keyboard is called scanning.
In order to detect which key is pressed from the matrix, we make row lines low one by one and read
the columns. Let’s say we first make Row1 low, and then read the columns. If any of the key in row1
is pressed, will make the corresponding column as low i.e. if second key is pressed in Row1, then
column2 will give low. So we come to know that key 2 of Row1 is pressed. This is how scanning is
done.
So to scan the keypad completely, we need to make rows low one by one and read the columns. If
any of the buttons is pressed in a row, it will take the corresponding column to a low state which tells
us that a key is pressed in that row. If button 1 of a row is pressed then Column 1 will become low, if
button 2 then column2 and so on...
As you can see no pin is connected to ground, over here the controller pin itself provides the ground.
_________________________________________________________________________________
www.vectorindia.org 92
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
#include<reg51.h>
#include”delay.h”
/*Main Function*/
main()
{
int row=0,col=0;// initialize variables for identify row and
// column
R0=R1=R2=R3=0; // 1st make all rows as zeros
C0=C1=C2=C3=1; // make all columns are ones
_________________________________________________________________________________
www.vectorindia.org 93
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 94
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
/* Column Check*/
if(C0==0)
col=0;
else if(C1==0)
col=1;
else if(C2==0)
col=2;
else if(C3==0)
col=3;
LCD also called as Liquid Crystal Display is very helpful in providing user interface as well as for
debugging purpose. The most common type of LCD controller is HITACHI 44780 which provides a
simple interface between the controller & an LCD. These LCD's are very simple to interface with the
controller as well as cost effective.
The LCD’s provide an easy way to get text display for an embedded system.The most commonly
used ALPHANUMERIC displays are 1x16 (Single Line & 16 characters), 2x16 (Double Line & 16
character per line) & 4x20 (four lines & Twenty characters per line).
_________________________________________________________________________________
www.vectorindia.org 95
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
UNDERSTANDING LCD
Pin-out
8 data pins D7:D0
Bi-directional data/command pins. Alphanumeric characters are sent in ASCII format.
RS: Register Select
RS = 0 -> Command Register is selected
RS = 1 -> Data Register is selected
R/W: Read or Write
0 -> Write, 1 -> Read
_________________________________________________________________________________
www.vectorindia.org 96
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Display data RAM (DDRAM) is where you send the characters (ASCII code) you want to see on the
LCD screen. It stores display data represented in 8-bit character codes. Its capacity is 80 characters
(bytes). Below you see DD RAM address layout of a 2*16 LCD.
In the above memory map, the area shaded in black is the visible display (For 16x2 displays). For
first line addresses for first 15 characters is from 00h to 0Fh. But for second line address of first
character is 40h and so on up to 4Fh for the 16th character. So if you want to display the text at
specific positions of LCD, we require to manipulate address and then to set cursor position
accordingly.
In the character generator RAM, we can define our own character patterns by program. CG RAM is
64 bytes, allowing for eight 5*8 pixel, character patterns to be defined.
_________________________________________________________________________________
www.vectorindia.org 97
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Registers
The HD44780 has two 8-bit registers, an instruction register (IR) and a data register (DR). The IR
stores instruction codes. The DR temporarily stores data to be written into DDRAM or CGRAM and
temporarily stores data to be read from DDRAM or CGRAM. Data written into the DR is
automatically written into DDRAM or CGRAM by an internal operation. . These two registers can
be selected by the register selector (RS) signal. See the table below:
Register Selection
RS R/W Operation
0 0 IR write as an internal operation (display clear, etc.)
0 1 Read busy flag (DB7) and address counter (DB0 to DB6)
1 0 DR write as an internal operation (DR to DDRAM or CGRAM)
1 1 DR read as an internal operation (DDRAM or CGRAM to DR)
When the busy flag is 1, the LCD is in the internal operation mode, and the next instruction will not
be accepted. When RS = 0 and R/W = 1 (see the table above), the busy flag is output to DB7 (MSB
of LCD data bus). The next instruction must be written after ensuring that the busy flag is 0.
LCD Commands
The LCD’s internal controllers accept several commands and modify the display accordingly. These
commands would be things like:
Clear screen
Return home
Shift display right/left
_________________________________________________________________________________
www.vectorindia.org 98
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Enable Display/Cursor
D - Turn Display on (1)/Off (0)
C - Turn Cursor on (1)/Off (0)
B - Cursor Blink On (1)/Off(0)
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. In short, you must always manipulate
EN when communicating with the LCD. EN is the LCD's way of knowing that you are talking to it.
If you don't raise/lower EN, the LCD doesn't know you're talking to it on the other lines.
_________________________________________________________________________________
www.vectorindia.org 100
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
If the LCD never come out from "busy" status because of some problems, the program will”hang,"
waiting for DB7 to go low. So in real applications it would be wise to put some kind of time limit on
the delay--for example, a maximum of 100 attempts to wait for the busy signal to go low. This would
guarantee that even if the LCD hardware fails, the program would not lock up.
/* Function Declarations*/
void init_lcd(void); // initialization of lcd
void cmd_lcd(unsigned char); // command mode of lcd
void data_lcd(unsigned char); // data mode of lcd
void write_lcd(unsigned char); // write command or data
void delay(unsigned int ); // for delay
/* Main Function */
main()
{
init_lcd(); // it calls initialize function
cmd_lcd(0x80); // call command to get cursor from
// starting position
_________________________________________________________________________________
www.vectorindia.org 101
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 102
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
/* Function Declarations*/
void init_lcd(void); // initialization of lcd
void cmd_lcd(unsigned char); // command mode of lcd
void data_lcd(unsigned char); // data mode of lcd
void write_lcd(unsigned char); // write data or command
void delay(unsigned int ); // for delay
/* Main Function*/
main()
{
init_lcd(); // it calls initialize function
cmd_lcd(0x80); // call command to get cursor from
// starting position
data_lcd('V'); // display "v" character on LCD
while(1); // stop here.
}
/* Function Definitions of LCD*/
void init_lcd()
{
cmd_lcd(0x02); // return cursor to home position
cmd_lcd(0x28); // 4-bit mode(it accepts only 4 data lines)
cmd_lcd(0x01); // clear the screen
cmd_lcd(0x0C); // display on with cursor off
cmd_lcd(0x06); // shift cursor right side
cmd_lcd(0x80); // cursor is in 1st position
}
_________________________________________________________________________________
www.vectorindia.org 103
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Timers
The 8051 has two timers/counters, they can be used either as
Timers to generate a time delay or as
Event counters to count events happening outside the microcontroller
Both Timer 0 and Timer 1 are 16 bits wide
Since 8051 has an 8-bit architecture, each 16-bits timer is accessed as two separate registers
of low byte and high byte
_________________________________________________________________________________
www.vectorindia.org 104
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Both timers 0 and 1 use the same register, called TMOD (timer mode), to set the various timer
operation modes
TMOD is an 8-bit register
The lower 4 bits are for Timer 0
The upper 4 bits are for Timer 1
In each case,
The lower 2 bits are used to set the timer mode
The upper 2 bits to specify the operation
_________________________________________________________________________________
www.vectorindia.org 105
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Timer Mode 2
In mode 2, the timer is set up as an eight bit counter which automatically reloads whenever an
overflow condition is detected. The low byte of the timer (TL0 or TL1) is used as the counter and the
high byte of the timer (TH0 or TH1) holds the reload value for the counter.
_________________________________________________________________________________
www.vectorindia.org 106
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
When the timer/counter overflows, the value in THx is loaded into TLx and the timer continues
counting from the reload value. Both timer 0 and timer 1 function identically in mode 2. Timer 1 is
often used in this mode to generate baud rates for the UART.
Timer Mode 3
In mode 3, timer 0 becomes two eight bit counters which are implemented in TH0 and TL0. The
counter implemented in TL0 maintains control of all the timer 0 flags, but the counter in TH0 takes
over the control flags in TCON from timer 1. This implies that timer 1 can no longer force interrupts,
however, it can be used for any purpose which will not require the overflow interrupt such as a baud
rate generator for the UART, or as a timer/counter which is polled by the software.
This is useful when an application must use a UART mode which requires baud rate generation from
timer 1 and also requires two timer/counters. When timer 1 is placed in mode 3 it simply freezes.
If C/T = 0, it is used as a timer for time delay generation. The clock source for the time delay is the
crystal frequency of the 8051
If desired, the timer/counters can force a software interrupt when they overflow. The TCON (Timer
Control) SFR is used to start or stop the timers as well as hold the overflow flags of the timers. The
TCON SFR is detailed below in Table A7. The timer/counters are started or stopped by changing the
timer run bits (TR0 and TR1) in TCON. The software can freeze the operation of either timer as well
as restart the timers simply by changing the TRx bit in the TCON register. The TCON register also
contains the overflow flags for the timers. When the timers overflow, they set their respective flag
(TF0 or TF1) in this register. When the processor detects a 0 to 1 transition in the flag, an interrupt
occurs if it is enabled. It should be noted that the software can set or clear this flag at any time.
Therefore, an interrupt can be prevented as well as forced by the software.
_________________________________________________________________________________
www.vectorindia.org 107
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Example 1
Indicate which mode and which timer is selected for each of the following.
(a) MOV TMOD, #01H (b) MOV TMOD, #20H (c) MOV TMOD, #12H
Solution
We convert the value from hex to binary. From Figure 9-3 we have:
(a) TMOD = 00000001, mode 1 of timer 0 is selected.
(b) TMOD = 00100000, mode 2 of timer 1 is selected.
(c) TMOD = 00010010, mode 2 of timer 0, and mode 1 of timer 1 are selected.
Example 2
Find the timer’s clock frequency and its period for various 8051-based systems, with the crystal
frequency 11.0592 MHz when C/T bit of TMOD is 0(it acts as a timer according to TMOD
register).
_________________________________________________________________________________
www.vectorindia.org 108
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Solution
2. After TH and TL are loaded with a 16-bit initial value, the timer must be started
This is done by SETB TR0 for timer 0 and SETB TR1 for timer 1
4. After the timer reaches its limit and rolls over, in order to repeat the process
TH and TL must be reloaded with the original value, and
TF must be reloaded to 0
_________________________________________________________________________________
www.vectorindia.org 109
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Example 3
In the following program, we create a square wave of 50% duty cycle (with equal portions high
and low) on the P1.5 bit. Timer 0 is used to generate the time delay.(with 12 MHz frequency)
CSEG AT 0
MOV TMOD, #01 ; Timer 0, mode 1(16-bit mode)
HERE: MOV TL0, #0CH ; TL0=0CH, the low byte
MOV TH0, #0FEH ; TH0=FEH, the high byte
CPL P1.5 ; toggle P1.5
ACALL DELAY ; It calls delay function (subroutine)
SJMP HERE ; It jumps to “HERE” label
DELAY:
SETB TR0 ; start the timer 0
AGAIN: JNB TF0, AGAIN ; monitor timer flag 0 until it rolls over
CLR TR0 ; stop timer 0
CLR TF0 ; clear timer 0 flag
RET ; It returns from the delay subroutine
END ; It ends the program
_________________________________________________________________________________
www.vectorindia.org 110
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
7. Timer 0 is stopped by the instruction CLR TR0. The DELAY subroutine ends and the process is
repeated.
Notice that to repeat the process, we must reload the TL and TH registers, and start the process is
repeated
Example 4
In Example 9-4, calculate the amount of time delay in the DELAY subroutine generated by the
timer. Assume XTAL = 12 MHz
Solution
The timer works with a clock frequency of 1/12 of the XTAL frequency; therefore, we have 12 MHz
/ 12 = 1 MHz as the timer frequency. As a result, each clock has a period of T = 1/1 MHz = 1us. In
other words, Timer 0 counts up each 1us resulting in delay = number of counts × 1us. The number of
counts for the roll over is FFFFH – FE0CH = 1F3H (499 decimal). However, we add one to 499
because of the extra clock needed when it rolls over from FFFF to 0 and raise the TF flag.
_________________________________________________________________________________
www.vectorindia.org 111
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
This gives 500 × 1us = 500us for half the pulse. For the entire period it is T = 2 × 500us = 1000us
i.e., 1ms as the time delay generated by the timer.
Example 5
In Example 4, calculate the frequency of the square wave generated on pin P1.5.
Solution
In the timer delay calculation of Example 4, we did not include the overhead due to instruction in
the loop. To get a more accurate timing, we need to add clock cycles due to these instructions in
the loop. To do that, we use the machine cycle from Table A-1 in Appendix A, as shown below.
CSEG AT 0
Cycles
HERE: MOV TL0, #0F2H 2
MOV TH0, #0FFH 2
CPL P1.5 1
ACALL DELAY 2
SJMP HERE 2
DELAY:
SETB TR0 1
AGAIN: JNB TF0, AGAIN 14
CLR TR0 1
CLR TF0 1
RET 2
END
Total-28
T = 2 × 28 × 1us = 56us and F = 17857.1 Hz
_________________________________________________________________________________
www.vectorindia.org 112
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Example 6
In the following program, we create a square wave of 50% duty cycle (with equal portions high
and low) on the P1.5 bit. Timer 0 is used to generate the time delay (with 12 MHz frequency) by
using timer0 mode 0.
_________________________________________________________________________________
CSEG AT 0
DELAY:
SETB TR0 ; start the timer 0
AGAIN: JNB TF0, AGAIN ; monitor timer flag 0 until it rolls over
CLR TR0 ; stop timer 0
CLR TF0 ; clear timer 0 flag
RET ; it returns from the delay subroutine
Maximum value is 8191-500=7691 (decimal) = 1111000001011 (Binary) =THX (8 bits) and TLX
(Lower 5 bits prescaler) now, hex value is F00BH.
_________________________________________________________________________________
www.vectorindia.org 113
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
SERIAL COMMUNICATION
Basics
Computers transfer data in two ways:
Parallel
Often 8 or more lines (wire conductors) are used to transfer data to a device that is only a few
feet away
Serial
To transfer to a device located many meters away, the serial method is used
The data is sent one bit at a time
At the transmitting end, the byte of data must be converted to serial bits using parallel-in-
serial-out shift register
At the receiving end, there is a serial-in- parallel-out shift register to receive the serial data
and pack them into byte
When the distance is short, the digital signal can be transferred as it is on a simple wire and
requires no modulation
If data is to be transferred on the telephone line, it must be converted from 0s and 1s to audio
tones
This conversion is performed by a device called a modem, “Modulator/demodulator”
_________________________________________________________________________________
www.vectorindia.org 114
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
It is possible to write software to use either of these methods, but the programs can be tedious and
long
There are special IC chips made by many manufacturers for serial communications
- UART (universal asynchronous Receiver transmitter)
- USART (universal synchronous-asynchronous Receiver-transmitter)
If data can be transmitted and received, it is a duplex transmission
If data transmitted one way a time, it is referred to as half duplex
If data can go both ways at a time, it is full duplex
This is contrast to simplex transmission
The start bit is always one bit, but the stop bit can be one or two bits
The start bit is always a 0 (low) and the stop bit(s) is 1 (high)
_________________________________________________________________________________
www.vectorindia.org 115
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 116
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
An interfacing standard RS232 was set by the Electronics Industries Association (EIA) in 1960
The standard was set long before the advent of the TTL logic family, its input and output
voltage levels are not TTL compatible
In RS232, a 1 is represented by -3 ~ -25 V, while a 0 bit is +3 ~ +25 V, making -3 to +3
undefined
IBM introduced the DB-9 version of the serial I/O standard
MAX 232
A line driver such as the MAX232 chip is required to convert RS232 voltage levels to TTL
levels, and vice versa
8051 has two pins that are used specifically for transferring and receiving data serially
- These two pins are called TxD and RxD and are part of the port 3 group (P3.0 and
P3.1)
- These pins are TTL compatible; therefore, they require a line driver to make them
RS232 compatible
We need a line driver (voltage converter) to convert the R232’s signals to TTL voltage levels
that will be acceptable to 8051’s TxD and RxD pins
_________________________________________________________________________________
www.vectorindia.org 118
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
To allow data transfer between the PC and an 8051 system without any error, we must make
sure that the baud rate of 8051 system matches the baud rate of the PC’s COM port
HyperTerminal function supports baud rates much higher than listed below
_________________________________________________________________________________
www.vectorindia.org 119
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
With XTAL = 11.0592 MHz, find the TH1 value needed to have the following baud rates.
(a) 9600 (b) 2400 (c) 1200
Solution
The machine cycle frequency of 8051 = 11.0592 / 12 = 921.6 kHz, and 921.6 kHz / 32 = 28,800 Hz
is frequency by UART to timer 1 to set baud rate.
Notice that dividing 1/12 of the crystal frequency by 32 is the default value upon activation of the
8051 RESET pin.
TF is set to 1 e
TF is set to 1 every 12 ticks, so it functions as a frequency divider
SBUF Register
SBUF is an 8-bit register used solely for serial communication
For a byte data to be transferred via the TxD line, it must be placed in the SBUF register
- The moment a byte is written into SBUF, it is framed with the start and stop
Bits and transferred serially via the TxD line
_________________________________________________________________________________
www.vectorindia.org 120
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
SBUF holds the byte of data when it is received by 8051 RxD line
- When the bits are received serially via RxD, the 8051 deframes it by eliminating the
stop and start bits, making a byte out of the data received, and then placing it in SBUF
SCON Register
SCON is an 8-bit register used to program the start bit, stop bit, and data bits of data framing, among
other things
SM0, SM1
They determine the framing of data by specifying the number of bits per character, and the start and
stop bits
_________________________________________________________________________________
www.vectorindia.org 121
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
SM2
This enables the multiprocessing capability of the 8051.
TI (transmit interrupt)
When 8051 finishes the transfer of 8-bit character
It raises TI flag to indicate that it is ready to transfer another byte
TI bit is raised at the beginning of the stop bit
RI (receive interrupt)
When 8051 receives data serially via RxD, it gets rid of the start and stop bits and places the byte in
SBUF register
It raises the RI flag bit to indicate that a byte has been received and should be picked up
before it is lost
RI is raised halfway through the stop bit
_________________________________________________________________________________
www.vectorindia.org 122
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
7. The TI flag bit is monitored with the use of instruction JNB TI, xx to see if the
Character has been transferred completely
8. To transfer the next byte, go to step 5
/* Write a program for the 8051 to transfer letter “A” serially at 9600 baud, continuously.
(11.0592 MHz frequency) */
CSEG AT 0
/* Write a program for the 8051 to receive bytes of data serially, and put them in P1, set the baud
rate at 9600, 8-bit data, and 1 stop bit */
CSEG AT 0
MOV TMOD, #20H ; timer 1, mode 2(auto reload)
MOV TH1, #-3 ; 9600 baud rate
MOV SCON, #50H ; 8-bit, 1 stop, REN enabled
SETB TR1 ; start timer 1
HERE: JNB RI, HERE ; wait for char to come in
MOV A, SBUF ; saving incoming byte in A
MOV P1, A ; send to port 1
CLR RI ; get ready to receive next byte
SJMP HERE ; keep getting data
END ; it ends the program
/* Write a program for the 8051 to receive bytes of data serially, transfer what we receive at 9600
baud, continuously. (11.0592 MHz frequency) */
CSEG AT 0
MOV TMOD, #20H ; timer 1, mode 2(auto reload)
MOV TH1, #-3 ; 9600 baud rate
MOV SCON, #50H ; 8-bit, 1 stop, REN enabled
SETB TR1 ; start timer 1
HEREE: JNB RI, HEREE ; wait for char to come in
MOV A, SBUF ; saving incoming byte in A
MOV SBUF, A ; Accumulator value to transfer
HERE: JNB TI, HERE ; wait for the last bit
CLR TI ; clear TI for next char
CLR RI ; get ready to receive next byte
SJMP HEREE ; keep getting data
END ; it ends the program
_________________________________________________________________________________
www.vectorindia.org 124
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
/* Write a program for the 8051 to transfer letter “A” continuously as well as parallel to receive
bytes of data serially at 9600 baud rate, transfer what we receive on P1 (f=11.0592 MHz
frequency) */
CSEG AT 0
MOV TMOD, #20H ; timer 1, mode 2(auto reload)
MOV TH1, #-3 ; 9600 baud rate
MOV SCON, #50H ; 8-bit, 1 stop, REN enabled
SETB TR1 ; start timer 1
AGAIN: MOV SBUF, #"A" ; Accumulator value to transfer
HERE: JNB TI, HERE ; wait for the last bit
Interrupts
An interrupt is an external or internal event that interrupts the microcontroller to inform it that a
device needs its service
A single microcontroller can serve several devices by two ways
Whenever any device needs its service, the device notifies the microcontroller by sending it
an interrupt signal
Upon receiving an interrupt signal, the microcontroller interrupts whatever it is doing and
serves the device
The program which is associated with the interrupt is called the interrupt service routine
(ISR) or interrupt handler
Polling
The microcontroller continuously monitors the status of a given device
When the conditions met, it performs the service
After that, it moves on to monitor the next device until every one is serviced
_________________________________________________________________________________
www.vectorindia.org 126
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Polling can monitor the status of several devices and serve each of them as certain conditions are met
The polling method is not efficient, since it wastes much of the microcontroller’s time by
polling devices that do not need service
Example
JNB TF, target
The advantage of interrupts is that the microcontroller can serve many devices (not all at the same
time)
Each devices can get the attention of the microcontroller based on the assigned priority
For the polling method, it is not possible to assign priority since it checks all devices in a
round-robin fashion
The microcontroller can also ignore (mask) a device request for service
This is not possible for the polling method
_________________________________________________________________________________
www.vectorindia.org 127
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
4. The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it
It starts to execute the interrupt service subroutine until it reaches the last instruction
of the subroutine which is RETI (return from interrupt)
5. Upon executing the RETI instruction, the microcontroller returns to the place where it was
interrupted
First, it gets the program counter (PC) address from the stack by popping the top two bytes of
the stack into the PC
Then it starts to execute from that address
Interrupts in 8051
Six Interrupts in 8051 those are mentioned in below
Reset – power-up reset
Two interrupts are set aside for the timers: one for timer 0 and one for timer 1
Two interrupts are set aside for hardware external interrupts
- P3.2 and P3.3 are for the external hardware interrupts INT0 (or EX1), and INT1 (or
EX2)
Serial communication has a single interrupt that belongs to both receive and transfer
Timer Interrupts
The timer flag (TF) is raised when the timer rolls over
In polling TF, we have to wait until the TF is raised
- The problem with this method is that the microcontroller is tied down while waiting for TF
to be raised, and can not do anything else
Using interrupts solves this problem and, avoids tying down the controller
- If the timer interrupts in the IE register is enabled, whenever the timer rolls over,
TF is raised, and the microcontroller is interrupted in whatever it is doing, and jumps to the
interrupt vector table to service the ISR
- In this way, the microcontroller can do other until it is notified that the timer has rolled over
1
_________________________________________________________________________________
www.vectorindia.org 129
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
/* Write a program that continuously get 8-bit data from P3 and sends it to P1 while
simultaneously creating a square wave of 200 μs period on pin P2.1. Use timer 0 to create the
square wave. Assume that XTAL = 11.0592 MHz. */
/*We will use timer 0 in mode 2 (auto reload). TH0 = 100/1.085 us = 92*/
/*upon wake-up go to main, avoid using memory allocated to Interrupt Vector
Table*/
CSEG AT 0
LJMP MAIN ; by-pass interrupt vector table
Note: Same process to Timer1 we have change timer mode TH and TL values after
check TF1 flag that will be discussed in class.
_________________________________________________________________________________
www.vectorindia.org 130
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 131
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
/* assume that the INT1 pin is connected to a switch that is normally high. Whenever it goes low,
it should turn on an LED. The LED is connected to P1.3 and is normally off. When it is turned on
it should stay on for a fraction of a second. As long as the switch is pressed low, the LED should
stay on. */
Solution:
CSEG AT 0000H
LJMP MAIN ; by-pass interrupt vector table
CSEG AT 30H
MAIN: MOV IE, #10000100B; enable external INT 1(IE= 84H)
HERE: SJMP HERE ; stay here until get interrupted
Note: Same process to Interrupt0 we have to change IE register values after check
INT0 (P3.2) pin that will be discussed in class.
On reset, IT0 (TCON.0) and IT1 (TCON.2) are both low, making external interrupt
level-triggered
_________________________________________________________________________________
www.vectorindia.org 132
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Edge-Triggered Interrupt
To make INT0 and INT1 edge triggered interrupts, we must program the bits of the TCON register
The TCON register holds, among other bits, the IT0 and IT1 flag bits that determine level- or
edge-triggered mode of the hardware interrupt
- IT0 and IT1 are bits D0 and D2 of the TCON register
- They are also referred to as TCON.0 and TCON.2 since the TCON register is
Bit addressable
_________________________________________________________________________________
www.vectorindia.org 133
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
/* Assume that pin 3.2 (INT0) is connected to a pulse generator, write a program in which the
falling edge of the pulse will send a high to P1.3, which is connected to an LED (or buzzer). In
other words, the LED is turned on and off at the same rate as the pulses are applied to the INT0
pin. */
CSEG AT 0000H
LJMP MAIN ; by-pass interrupt vector table
CSEG AT 30H
MAIN: SETB TCON.0 ; make INT0 edge-triggered int.
MOV IE, #10000001B ; enable external INT 0(IE= 81H)
HERE: SJMP HERE ; stay here until get interrupted
_________________________________________________________________________________
www.vectorindia.org 134
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
In the 8051 there is only one interrupt set aside for serial communication
This interrupt is used to both send and receive data
If the interrupt bit in the IE register (IE.4) is enabled, when RI or TI is raised the 8051 gets
interrupted and jumps to memory location 0023H to execute the ISR
In that ISR we must examine the TI and RI flags to see which one caused the interrupt and
respond accordingly
/* Write a program in which the 8051 gets data from P1 and sends it to P2 continuously while
incoming data from the serial port is sent to P0. Assume that XTAL=11.0592. Set the baud rata at
9600 */
CSEG AT 0000H
LJMP MAIN
CSEG AT 23H
LJMP SERIAL ; jump to serial interrupt ISR
CSEG AT 30H
MAIN: MOV P1, #0FFH ; make P1 an input port
MOV IE, 10010000B ; enable serial int.
MOV TMOD, #20H ; timer 1, auto reload
MOV TH1, #0FDH ; 9600 baud rate
MOV SCON, #50H ; 8-bit, 1 stop, “REN” enabled
SETB TR1 ; start timer 1
BACK: MOV P1, A ; read data from A send it to P1
MOV P2, A ; also send it to P2
SJMP BACK ; stay in loop indefinitely
_________________________________________________________________________________
www.vectorindia.org 135
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
CSEG AT 100H
SERIAL: JB TI, TRANS ; jump if TI is high
MOV A, SBUF ; otherwise due to receive
_________________________________________________________________________________
www.vectorindia.org 136
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
main()
{
unsigned char x=0x01;// declare and assign some value to "x"
EA=EX0=ET0=ES=IT0=1; // Enable 3 interrupts (Ext INT0, Timer0,
// Serial Interrupt)
SCON=0x50; // select standard UART mode and Enable
// reception and transmission
TMOD=0x21; // Select timer1 mode2 for UART and
// timer0 mode1 for timer0 interrupt
TH1=TL1=-3; // pass "-3" value on TH1 for setting the
// baud rate (9600)
TR1=1; // set timer1 run bit then it starts the timer1
TR0=1; // set timer0 run bit then it starts the timer0
_________________________________________________________________________________
www.vectorindia.org 137
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 138
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 139
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 140
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 141
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Now it opens one dialogue box, select path where you want to save your project. So, click on
scroll bar click on one drive where you want to save.
_________________________________________________________________________________
www.vectorindia.org 142
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Click on create new folder icon to save your project in that folder
_________________________________________________________________________________
www.vectorindia.org 143
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 144
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Double click on that folder now it opens another dialogue box to save your project
Give project name in “File name” blank with out any extension
_________________________________________________________________________________
www.vectorindia.org 145
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 146
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
In that dialogue box they given one list it’s related to manufacturer name of IC’s. Select one
manufacturer name related to your target board.
_________________________________________________________________________________
www.vectorindia.org 147
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Search for your required IC with the help of Scroll bar select that IC click on that IC name for
example select “89s52”
_________________________________________________________________________________
www.vectorindia.org 148
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
It opens one dialogue box it’s related to start up code for 8051 there is no need of start up
code. So, click on “NO” button
_________________________________________________________________________________
www.vectorindia.org 149
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Now Target is created with the project name of (8051). Project name is your wish
_________________________________________________________________________________
www.vectorindia.org 150
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 151
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Save that file for that again click on “File” menu bar click on save as (short cut key (ctrl+s))
_________________________________________________________________________________
www.vectorindia.org 152
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Give any name in “File name” blank with extension of “.asm” or “.c” based on program
Note: If you want to practice in “VECTOR Lab” save your projects and files in your “server
ID”. Otherwise you will loss your data. If any doubts in this concept plesae be contact your
concern Lab Co-ordinators”.
_________________________________________________________________________________
www.vectorindia.org 153
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 154
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Now file also created with name (Observe above menu bar it shows path where we saved and
name of the project and file like for example[D:\8051\test.asm]
_________________________________________________________________________________
www.vectorindia.org 155
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
If it is C source file [D:\8051\test.c]. Selection of path project and file names are based on
user requirement it’s not fixed. What you selected that one only it shows above menu bar.
4) Which file you want to compile add that file to source group for that we have to follow these steps
Select source group on project window
_________________________________________________________________________________
www.vectorindia.org 156
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Right click on that source group in this it’s named as “Source Group 1”
_________________________________________________________________________________
www.vectorindia.org 157
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Now it opens one dialogue box in this it shows which file you want to add and which file you
want to compile (by default it shows c source files)
If you want to compile asm files select file type as “Asm Source File”. Then it listed total
overall asm files
_________________________________________________________________________________
www.vectorindia.org 158
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Now “asm files” are opened then you can select required file name for writing program and
for compilation
_________________________________________________________________________________
www.vectorindia.org 159
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Now file is added to source group (File name is not visible to you then you can click on left
side “+” symbol of source group. Double click on file name.
_________________________________________________________________________________
www.vectorindia.org 160
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Now you can write program if program is not available in that file
Before writing the program first of all you have to know about Addressing modes,
instruction sets and Assembler directives. So, first you can read after you can write
program
Every time you can save that file with the short cut key (CTRL+S)
After you can compile for that click on “project” on menu bar
_________________________________________________________________________________
www.vectorindia.org 161
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Now check the output on output window. In that it shows errors, warnings and how much
size your program (blue color marking is output window)
_________________________________________________________________________________
www.vectorindia.org 162
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
5) Next if you want to see the output on this keil you have to know debugging process for that
follows these steps
_________________________________________________________________________________
www.vectorindia.org 163
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Now you can do step by step execution for that click on “Debug” on menu bar
Click on “Step” short cut key (F11) (or) same symbol is available in debug tool bar
_________________________________________________________________________________
www.vectorindia.org 164
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Another way to see the output your program output is a 34h that one you can see on
memory window example “A” register is internal RAM. So, you can type D: address on
memory window. Now “A” register address is 0xE0 (or) 0E0H. D:0E0h
_________________________________________________________________________________
www.vectorindia.org 165
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
If you want to see the output on ports then you can select peripherals and click on desired
port.
_________________________________________________________________________________
www.vectorindia.org 166
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
If you want to see project window to see output on general purpose registers, A and B and
some SFRs, another one is memory window to see data on particular memory, another one is
Disassembly window to see the program in opcodes format, another one is watch & call stack
window to see user defined variables output those all are available in “View” on menu bar.
Which one wants you can click on that window it’s opened if you don’t want again you can
click on same “View” button on menu bar and which window you don’t want click on that it
disabled.
On memory window if you want to see the data on code memory type C: address, and for
external memory type X: address and for internal data type D: address
If you want to come out from the debugging process again click on “Debug” on menu bar and
click on start/stop debugging (or) press CTRL+F5 (or) click on “d” symbol on debug tool
bar.
_________________________________________________________________________________
www.vectorindia.org 167
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Now you can see all windows which are explained in previously.
If you want to create another project follow same process how to create project before that
one first close previous project.
First come out from the debugging and after click on “Project” on Menu bar after you can
click on “close project” option.
_________________________________________________________________________________
www.vectorindia.org 168
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
If you want to create new file follow same process “How to create file” we discussed
previously. Before that one close the file
Click on “File” on menu bar and click on “Close” option.
Next remove file from source group on project window for that which file you want to
remove on that you can give right click after click on “remove file”.
_________________________________________________________________________________
www.vectorindia.org 169
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Again if you want to create and save the project and file we have to follow same above process.
_________________________________________________________________________________
www.vectorindia.org 170
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 171
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 172
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Click on “open”
It opens one dialogue box in that select path and your filename
_________________________________________________________________________________
www.vectorindia.org 173
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 174
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
It opens one dialogue box like below set your desired frequency
_________________________________________________________________________________
www.vectorindia.org 175
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 176
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
If you want to save your hex file in particular place click on “select folder for objects” select
path where you want to save
_________________________________________________________________________________
www.vectorindia.org 177
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
It opens one dialogue box from there you can set your path
_________________________________________________________________________________
www.vectorindia.org 178
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
After you can save press CTRL+S and build your target press F7 now hex file is created
See output window it shows hex file name including with path.
_________________________________________________________________________________
www.vectorindia.org 179
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
SCHEMATICS
POWER SUPPLY:
_________________________________________________________________________________
www.vectorindia.org 180
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
AT89S52:
_________________________________________________________________________________
www.vectorindia.org 181
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
IN SYSTEM PROGRAMMERS:
_________________________________________________________________________________
www.vectorindia.org 182
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
_________________________________________________________________________________
www.vectorindia.org 183
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
7-SEGMENT DISPLAY’S
_________________________________________________________________________________
www.vectorindia.org 184
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
ALPHANUMERIC LCD:
_________________________________________________________________________________
www.vectorindia.org 185
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
GRAPHICAL LCD:
_________________________________________________________________________________
www.vectorindia.org 186
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
MAX 232:
_________________________________________________________________________________
www.vectorindia.org 187
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
DS18B20 : IR RX :
_________________________________________________________________________________
www.vectorindia.org 188
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
SPI(MCP3204):
_________________________________________________________________________________
www.vectorindia.org 189
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
I2C:
_________________________________________________________________________________
www.vectorindia.org 190
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
L293D:
ULN2003:
_________________________________________________________________________________
www.vectorindia.org 191
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
ASSIGNMENTS
8051 Micro controller (mandatory) Programs On
1. Data Transfer Operations…………………………………………………………
2. Logical & Bit Operations………………………………………………………….
3. Arithmetic Operations……………………………………………………………
4. Branching Operations…………………………………………………………….
5. Interfacing of LED’s ……………………………………………………………..
6. Interfacing of Switches, LED’s/Buzzer………………………………………….
7. Interfacing Seven Segment Display & switches…………………………………
8. Interfacing of LCD………………………………………………………………..
9. Interfacing 4x4 Matrix Keypad & LCD/Seven Segment…………………………
10. Timers/Counters……………………………………………………………………
11. Serial Communication using UART peripheral’s Standard UART Mode ………..
12. Interrupts…………………………………………………………………..
Project on any ONE of the below
13. SMS Matrix Keypad……………………………………………………………….
14. Interfacing of I2C EEPROM AT24C01 & LCD/UART…………………………..
15. Interfacing of I2C RTC DS1307 & LCD/UART…………………………………..
16. Interfacing of SPI ADC MCP3201 & LCD/UART……………………………..
17. Interfacing of 128*64 Graphical LCD……………………………………………..
18. IR decoding, Philips Remote Control RC5 protocol implementation ……………
19. Smart Card Authentication…………………………………………………………
20. Memory Mapped I/0 using 8255 PPI………………………………………………
21. Temperature Sensing using 1-wire protocol………………………………………..
22. Implementing a Round Robin Scheduler……………….…………………………..
23. Multitasking Application using Real Time OS…………………………………….
24. RF Based Automation………………………………………………………………
25. Distance measurement with ultrasonic sensor...........................................................
_________________________________________________________________________________
www.vectorindia.org 192
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
1. Add 55h and 66h and put the result in r4 and r5 of bank 2
2. Add the content in 55h,56h and 57h and put the result a(msb) and b(lsb)
3. Add the byte in intram loc 45h with extram loc 45h
4. Sub the contents of r0 and r1 and put the res in r0 of bank1
5. Multiply FFh and FFH and store the result in r2 and r3
6. Div 58 by 5 and store the result in r0 and r1
7. Add one to every external ram location from 10h to 13h
8. Square the content of acc and store the result in ext ram loc 00 and 01
9. Store 0fdh in tl0 and increment it by 2 and put the res in th0
10. Store 0ech in r5 and convert it to bcd and store res in r6
11. Add the content of tl0 and tl1 and store the res in th0
12. Add the content of p0 with p1 and store the res in p2
9. Write a program to add the following numbers and save the result in R2, R3. The data is
stored in on-chip ROM.
MYDATA: DB 53, 94, 56, 92, 74, 65, 43, 23, 83
10. Write a sub-routine that adds to 8-bit numbers and stores the result in r6 (MSB) and r7(LSB)
and call it.
11. Write a sub-routine to create a delay of about 1 ms and call it.
12. Write a sub-routine to create any approximate delay within of 1 ms up to 100ms.
Interfacing of LEDs
1. Flash an LED connected to port line using complement logic at the rate of 1 second for 10
times and stop.
2. Flash an LED connected to port line using the set and clear logic each at the rate of 1second
for 10 times and stop.
3. Display on the LEDS connected to port the pattern as explained:
First all the LEDS should be off and remaining in this state for about 1 sec.
After 1 second laps switch on the only LED0 (bit 0)
After 2 seconds laps switch on the only LED1 (bit 1)
………………………………………………………
………………………………………………………
After 8 seconds laps switch on the only LED7 (bit 7)
Switch of all the LEDS for about 3 secs.
Repeat this pattern for 5 times ONLY.
1. Read the status of momentary switch (SW) connected to any port pin and display it on the
LED & make the buzzer beep connected to another port pins.
_________________________________________________________________________________
www.vectorindia.org 195
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
2. A momentary switch (SW) is connected P2.5 and four LEDs are connected to lower nibble of
port 0.Your program should behave as follows :
Depending on the number of times the SW pressed -
The 1st time, LED 0 should be ON only,
The 2nd time, LED 1 should be ON only,
The 3rd time, LED 2 should be ON only,
The 4th time, LED 3 should be ON only,
If pressed here after none should be ON until system reset.
3. Read the status of all momentary switches SW’s connected to PORT 0 and display their
status of being pressed on corresponding LEDS connected to PORT 2 infinitely.
4. Read the status of 4 momentary switches SW’s connected to lower nibble of PORT 0 and
display their status on an LED connected to P2.0 only.
Interfacing of LCD
1. Display and Scroll the string “VECTOR”, towards right, on Line 1 of LCD until it disappears
from the screen.
2. Display and circularly Scroll the string “VECTOR”, towards right, on Line 1 of LCD
infinitely on the screen.
3. Display 4 new customized characters.
_________________________________________________________________________________
www.vectorindia.org 196
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Serial Communication:
1) Write an ALP to serially transmit the message “Welcome to VECTOR” on serial window/pc
hyper terminal window.
2) Write an ALP to infinitely receive any character then re-transmit its ASCII value in decimal and
hex format. Output should be seen as for example below
Output: Received ‘A’ 65 41
Received ‘a’ 97 61
……………………..
3) Using the concept of multiple file assembly, assuming three files, say mainfile.asm, serial.asm
and delay.asm are edited as mentioned below
Mainfile.asm – contains the main logic of the application which invokes routines from other files
Serial.asm - contains UART input and output routines
Delay.asm – contains loop delay and timer delay routine
Write an ALP to show 00 – 99 secs counters on the serial window.
4) Write an Embedded-C program for demonstrating full duplex feature of UART in mode 1.
_________________________________________________________________________________
www.vectorindia.org 197
Training Material – 8051 Microcontroller
____________________________________________________________________________________________________________
Interrupts
1.Test with some form of visual outputs the response of the microcontroller to various interrupt
sources.
_________________________________________________________________________________
www.vectorindia.org 198