MC & ESY Notes
MC & ESY Notes
MC & ESY Notes
POLYTECHNIC
ROURKELA
DEPARTMENT OF ELECTRONICS
AND TELECOMMUNICATION
ENGINEERING
LECTURE NOTES
Embedded system:
An embedded system is a system that has embedded software & hardware, which
makes it a system dedicated for an application or specific part of an applications
or product or a part of a larger system.
Embedded system=programming in electronics.
Cash register, alarm system, card reader, product scanner, curb side check in
automated teller machine (ATM)
5. Automobiles:-
Transmission control , cruise control, fuel injection, anti-lock brakes & reactive
suspension
Air bags, anti-lock braking system (ABs), engine control, door lock, GPS system,
vehicular ad-hoc network (VANET)
6. Communication:-
1. Single functional: -
An embedded system usually executes only one program, repeatedly.
For Example: - a pager is always a pager
The circuit size should be small enough to fit on a single chip and must perform
fast enough to process data in real time & consume minimum power to extend
battery-life.
3. Reactive& Real time:-
It should continuously react to the changes in the system environment and must
compute certain results in real time without any delay
A reactive system is reacting on a given input. Like in an over when we press the
button to start cooking, it takes input & start acting. This type of system is the
reactive system
But what happens it the over responds in a random interval like some time it start
in 30 sec & sometime in 5 minutes. The point is there should be some time limit to
start action. This called deadline
A DIGITAL CAMERA:-
The A2D and D2A circuits convert analog images to digital and digital to analog
respectively.
The CCD processor is a charge-coupled device pre-processor
The JPEG codec compresses and decompresses an image using the JPEG2
compression standard, enabling compact storage in the limited memory of the
camera.
The pixel coprocessor aids in rapidly displaying images.
The memory controller controls access to a memory chip also found in the camera,
while the DMA controller enables direct memory access without requiring the use
of the microcontroller.
The UART enables communication with a PC’s serial port for uploading video
frames, while the ISA bus interface enables a faster connection with a PC’s ISA bus.
The LCD ctrl and Display ctrl circuit control the display of images on the camera’s
liquid-crystal display device.
A multiplier/Accumulator circuit assists with certain digital signal processing.
The heart of the system is a microcontroller, which is a processor that controls
the activities of all the other circuit. Each device as a processor designed for a
particular task, while the microcontroller is a more general processor designed for
general tasks.
The general –purpose processor is designed to serve several applications with the
idea of being able to sell the maximum number of devices.
One feature of such a processor is a program memory-the designer does not know
what program will run on the processor, so the program cannot be inserted with
a digital circuit.
Another feature is a general data path this should have the capacity to handle a
variety of computations-thus it will have large register file with additional general
purpose arithmetic logic unit (ALU).
An embedded system simply uses a general-purpose processor, by programming
the processor’s memory to carry out the required functionality.
For example, since the example counts from 1 to N, we add an index register.
The index register will be loaded with N, and will then count down to zero (‘0’),
at which time it will assert a status line read by the controller.
The example has only one other value, we add only one register labeled total to
the data path.
Since the example’s only arithmetic operation is addition, we add a single adder
to the data path.
Since the processor only executes this one program, we hardware the program
directly into the control logic.
The Block diagram of an application specific processor is given below. You can see
there is no program memory in this. It is designed for particular types of input.
MICROCONTROLLERS:-
1.5 IC TECHNOLOGY:-
• Every processor must eventually be implemented on an IC.
• An IC (Integrated Circuit), often called a “chip,” is a semiconductor device consisting
of a set of connected transistors and other devices.
• A number of different processes exist to build semiconductors, the most popular of
which is CMOS (Complementary Metal Oxide Semiconductor).
• Semiconductors consist of numerous layers as shown in the figure given below.
• The bottom layers form the transistors. The middle layers form logic gates. The top
layers connect these gates with wires. These layers can be created by depositing
photo-sensitive chemicals on the chip surface and then shining light through masks
to change regions of the chemicals. A set of masks is often called a layout. The
narrowest line that we can create on a chip is called the feature size.
Full Custom / VLSI:-
• In a full-custom IC technology, we optimize all layers for our particular embedded
system’s digital implementation.
• Such optimization includes placing the transistors to minimize interconnection
lengths, sizing the transistors to optimize signal transmissions and routing wires
among the transistors.
• Once all the masks are completed, then we send the mask specifications to a
fabrication plant that builds the actual ICs.
• Full-custom IC design, often referred to as VLSI (Very Large Scale Integration) design,
has very high NRE cost and long turnaround times (typically months) before the IC
becomes available, but can yield excellent performance with small size and power.
• It is usually used only in high-volume or extremely performance-critical applications.
• In an ASIC (Application-Specific IC) technology, the lower layers are fully or partially
built, leaving us to finish the upper layers.
• In a gate array technology, the masks for the transistor and gate levels are already
built (i.e., the IC already consists of arrays of gates).
• The remaining task is to connect these gates to achieve our particular
implementation.
• In a standard cell technology, logic-level cells (such as an AND gate or an AND-
ORINVERT combination) have their mask portions pre-designed, usually by hand.
• Thus, the remaining task is to arrange these portions into complete masks for the gate
level, and then to connect the cells.
• ASICs are by far the most popular IC technology, as they provide for good
performance and size, with much less NRE cost than full-custom IC’s.
PLD:
• In a PLD (Programmable Logic Device) technology, layers implement a
programmable circuit, where programming has a lower-level meaning than a
software program.
• The programming that takes place may consist of creating or destroying connections
between wires that connect gates, either by blowing a fuse, or setting a bit in a
programmable switch.
• Small devices, called programmers, connected to a desktop computer can typically
perform such programming.
• PLD's of two types, simple and complex. One type of simple PLD is a PLA
(Programmable Logic Array), which consists of a programmable array of AND gates
and a programmable array of OR gates.
• Another type is a PAL (Programmable Array Logic), which uses just one
programmable array to reduce the number of expensive programmable components.
• One type of complex PLD, growing very rapidly in popularity over the past decade, is
the FPGA (Field Programmable Gate Array), which offers more general connectivity
among blocks of logic, rather than just arrays of logic as with PLAs and PALs, and is
thus able to implement far more complex designs. PLDs offer very low NRE cost and
almost instant IC availability.
• They are typically bigger than ASICs, may have higher unit cost, may consume more
power, and may be slower (especially FPGAs). They still provide reasonable
performance, though, so are especially well suited to rapid prototyping.
UNIT-2: MICROCONTROLLER 8051 ARCHITECTURE
1.1 DIFFERENCE BETWEEN MICROCONTROLLER &GENERAL
PURPOSE MICROPROCESSOR:
MICROCONTROLLER:
Microcontroller is like a mini computer with a CPU along with RAM, ROM, serial
ports, timers, and IO peripherals all embedded on a single chip.
It’s designed to perform application specific tasks that require a certain degree of
control such as a TV remote, LED display panel, smart watches, vehicles, traffic light
control, temperature control, etc.
It’s a high-end device with a microprocessor, memory, and input/output ports all
on a single chip.
It’s the brains of a computer system which contains enough circuitry to perform
specific functions without external memory.
Since it lacks external components, the power consumption is less which makes it
ideal for devices running on batteries.
Simple speaking, a microcontroller is complete computer system with less external
hardware.
MICROPROCESSOR:
Microprocessor Microcontroller
Microprocessor contains ALU, General Microcontroller contains the circuitry of
purpose registers, stack pointer, microprocessor, and in addition it has
program counter, clock timing circuit, built in ROM, RAM, I/O Devices,
interrupt circuit Timers/Counters etc.
It has many instructions to move data It has few instructions to move data
between memory and CPU between memory and CPU
Few bit handling instruction It has many bit handling instructions
Less number of pins are multifunctional More number of pins are multifunctional
Single memory map for data and Separate memory map for data and code
code (program) (program)
Access time for memory and IO are Less access time for built in memory and
more IO.
Microprocessor based system requires It requires less additional hardware’s
additional hardware
More flexible in the design point of view Less flexible since the additional circuits
which is residing inside the
microcontroller is fixed for a particular
microcontroller
Large number of instructions with Limited number of instructions with
flexible addressing modes few addressing modes
2. 2 ARCHITECTURE OF 8051:
CPU:
8051 has an 8 bit CPU.
This is where all 8-bot arithmetic and logic operations are performed.
It has the following components.
Example:
ADD A, R0 ; Adds contents of A register and R0 register and stores the result
in A register.
ANL A, R0 ; Logically ANDs contents of A register and R0 register and stores
the result in A register.
CPL P0.0 ; Complements the value of P0.0 pin.
A – REGISTER (ACCUMULATOR):
It is an 8-bit register.
In most arithmetic and logic operations, A register hold the first operand and
also gets the result of the operation.
Moreover, it is the only register to be used for data transfers to and from
external memory.
Example:
ADD A, R1 ; Adds contents of A register and R1 register and stores the result
in A register.
MOVX A, @DPTR ; A gets the data from External RAM location
pointed by DPTR
B – REGISTER:
It is an 8-bit register.
It is dedicated for Multiplication and Division.
It can also be used in other operations.
Example:
MUL AB; Multiplies contents of A and B registers. Stores 16-bit result in B
and A registers.
SP – STACK POINTER
It is an 8-bit register.
It contains address of the top of stack. The Stack is present in the Internal RAM.
Internal RAM has 8-bit addresses from 00H… 7FH. Hence SP is an 8-bit
register.
It is affected during Push and Pop operations. During a Push, SP gets
incremented.
During a Pop, SP gets decremented.
Example:
SETB PSW.3 ; Makes PSW.3 1
CLR PSW.4 ; Makes PSW.40
RESET:
It is used to reset the 8051 microcontroller. On reset PC becomes 0000H.
This address is called the reset vector address.
From here, 8051 executes the BIOS program also called the Booting program or
the monitor program.
It is used to set-up the system and make it ready, to be used by the end-user.
ALE:
It is used to enable the latching of the address. The address and data buses are
multiplexed.
This is done to reduce the number of pins on the 8051 IC.
Once out of the chip, address and data have to be separated that is called de-
multiplexing.
This is done by a latch, with the help of ALE signal. ALE is “1” when the bus
carries address and “0” when the bus carries data.
This informs the latch, when the bus is carrying address so that the latch
captures only address and not the data.
EA’
It decides whether the first 4 KB of program memory space (0000H… 0FFFH)
will be assigned to internal ROM or External ROM.
If EA = 0, the External ROM begins from 0000H.
In this case the Internal ROM is discarded. 8051 now uses only External ROM.
If EA = 1, the External ROM begins from 1000H.
In this case the Internal ROM is used. It occupies the space 0000H…0FFFH.
In modern FLASH ROM versions, this pin also acts as VPP (12 Volt
programming voltage) to write into the FLASH ROM.
PSEN’
8051 has a 16-bit address bus (A15-A0).
This should allow 8051 to access 64 KB of external Memory as 2 16 = 64 KB.
Interestingly though, 8051 can access 64 KB of External ROM and 64 KB of
External RAM, making a total of 128 KB.
Both have the same address range 0000H to FFFFH.
This does not lead to any confusion because there are
separate control signals for External RAM and External
ROM.
RD and WR are control signals for External RAM.
PSEN is the READ signal for External ROM.
It is called Program Status Enable as it allows reading
from ROM also known as Program Memory. Having
separate control signals for External RAM and External
ROM actually allows us to double the size of the external
memory to a total of 128 KB from the original 64 KB.
P0.0-P0.7
P1.0-P1.7
P2.0-P2.7
P3.0-P3.7
8051 Programming
MEMORY ORGANIZATION:
During the runtime, microcontroller uses two different types of memory: one
for holding the program being executed (ROM memory), and the other for
temporary storage of data and auxiliary variables (RAM memory).
Depending on the particular model from 8051 family, this is usually few
kilobytes of ROM and 128/256 bytes of RAM.
This amount is built-in and is sufficient for common tasks performed
"independently" by the MCU.
However, 8051 can address up to 64KB of external memory.
MEMORY ARCHITECTURE:
1. VON-NEUMAN ARCHITECTURE:
Von Neumann architectures are computer architectures that use the same
storage device for both instructions and data.
By treating the instructions in the same way as the data, the machine could
easily change the instructions.
In other words the machine was reprogram able. Because the machine did not
distinguish between instructions and data, it allowed a program to modify or
replicate a program.
2. HARVARD ARCHITECTURE
The term Harvard architecture originally referred to computer architectures
that uses physically separate storage devices for their instructions and data.
Harvard architecture has separate data and instruction busses, allowing
transfers to be performed simultaneously on both buses.
Parallelism means that fetches for the next instruction can take place during the
execution of the current instruction, without having to either wait for a "dead"
cycle of the instruction's execution or stop the processor's operation while the
next instruction is being fetched.
MEMORY ORGANIZATION:
The 8051 has two types of memory and these are Program Memory and Data
Memory.
Program Memory (ROM) is used to permanently save the program being executed,
while Data Memory (RAM) is used for temporarily storing data and intermediate
results created and used during the operation of the microcontroller.
Depending on the model in use (we are still talking about the 8051
microcontroller family in general) at most a few Kb of ROM and 128 or 256 bytes
of RAM is used.
All 8051 microcontrollers have a 16-bit addressing bus and are capable of
addressing 64 kb memory.
Internal ROM
External ROM
Internal RAM
External RAM
Being based on Harvard Model, 8051 stores programs and data in separate
memory spaces. Programs are stored in ROM, whereas data is stored in RAM.
Microcontrollers are used in appliances.
Washing machines, remote controllers, microwave ovens are some of the
EXAMPLES:
Here programs are generally permanent in nature and very rarely need to be
modified. Moreover, the programs must be retained even after the device is
completely switched off. Hence programs are stored in permanent (non-
volatile) memory like ROM.
Data on the other hand is continuously changed at runtime. For example
current temperature, cooking time etc. in an oven.
Such data is not permanent in nature and will certainly be modified in every
usage of the device.
Hence Data is stored in writeable memory like RAM.
However, sometimes there is permanent data, such as ASCII codes or 7-
segment display codes. Such data is stored in ROM, in the form of Look up
tables and is accessed using a dedicated addressing mode called Indexed
Addressing mode. We will discover this in more depth in further topics.
We are now going to take a closer look at all four memories.
ROM ORGANIZATION / CODE MEMORY / PROGRAM MEMORY
REGISTER BANKS:
The first 32 locations (Bytes) of the Internal RAM from 00H… 1FH, are
used by the programmer as general purpose registers.
Having so many general purpose registers makes programming easier
and faster.
But as a downside, this also vastly increases the number of opcodes
(refer my class lectures for detailed understanding of this).
Hence the 32 registers are divided into 4 banks, each having 8
Registers R0… R7.
The first 8 locations 00H… 07H are registers R0… R7 of bank 0.
Similarly locations 08H… 0FH are registers R0… R7 of bank 1 and so
on. A register can be addressed using its name, or by its address.
E.g. Location 00H can be accessed as R0, if Bank 0 is the active bank.
MOV A, R0; “A” register gets data from register R0.
It can also be accessed as Location 00H, irrespective of which bank is the active
bank.
MOV A, 00H; “A” register gets data from Location 00H.
The appropriate bank is selected by the RS1, RS0 bits of PSW.
Since PSW is available to the programmer, any Bank can be selected at run-
time.
Bank 0 is selected by default, on reset.
Here is something very interesting to know and will also help you understand
further topics. The entire internal RAM is of 128 bytes so the address range is
00H… 7FH.
The bit addressable area has 128 bits so its bit addresses are also 00h… 7FH.
This means every address 00H… 7FH can have two meanings, it could be a byte
address or a bit address.
This does not lead to any confusion, because the instruction in which
we use the address, will clearly indicate whether it is a bit operation
or a byte operations.
SETB, CLR etc. are bit ops whereas ADD, SUB etc. are byte
operations.
SETB 00H; this is a bit operation. It will make Bit location 00H
contain a value “1”.
MOV A, 00H; this is a byte operation. A” register will get 8-bit data
from byte location 00H.
SFRs are 8-bit registers. Each SFR has its own special function.
They are placed inside the Microcontroller.
They are used by the programmer to perform special functions like controlling the
timers, the serial port, the I/O ports etc.
As SFRs are available to the programmer, we will use them in instructions. This
causes another problem. SFRs are registers after all, and hence using them would
tremendously increase the number of opcodes to reduce the number of opcodes,
SFRs are allotted addresses. These addresses must not clash with any other
addresses of the existing memories
Incidentally, the internal RAM is of 128 bytes and uses addresses only from 00H…
7FH. This gives an entire range of addresses from 80H… FFH completely unused and
can be freely allotted to the SFRs. Hence SFRs are allotted addresses from 80H…
FFH.
It is not a co-incidence that these addresses are free. The Internal RAM was
restricted to 128 bytes instead of 256 bytes so that these addresses are free for SFRs.
To avoid this problem, even the bits of the SFRs are allotted addresses. These are bit
addresses, which are different from byte addresses. These bit addresses must not
clash with those of the bit addressable area of the Internal RAM. Amazingly, even
the bit addresses in the Internal RAM are 00H… 7FH (again 128 bits), keeping bit
addresses 80H… FFH free to be used by the SFR bits.
So bit addresses 80H… FFH are allotted to the bits of various SFRs.
Port 0 has a byte address of 80H and its bit addresses are from 80H… 87H.
A byte operation at address 80H will affect entire Port0.
E.g.-MOV A, P0; this refers to Byte address 80H that’s whole Port 0. 12) A bit
Operation at 80H will affect only P0.0.
E.g. SETB P0.0; this refers to bit address 80H that’s Port0.0
It is an 8-bit register.
It is also called the “Flag register”, as it mainly contains the status flags.
These flags indicate status of the current result.
They are changed by the ALU after every arithmetic or logic operation.
The flags can also be changed by the programmer.
PSW is a bit addressable register.
Each bit can be individually set or reset by the programmer.
The bits can be referred to by their bit numbers (PSW.4) or by their name (RS1).
CY - CARRY FLAG
It indicates the carry out of the MSB, after any arithmetic operation.
If CY = 1, There was a carry out of the MSB
If CY = 0, There was no carry out of the MSB
P - PARITY FLAG
The initial 32 locations (bytes) of the Internal RAM are available to the
programmer as registers.
Having so many registers makes programming easier and faster.
Naming R0… R31, would tremendously increase the number of opcodes.
Hence the registers are divided into 4 banks: Bank0… Bank3.
Each bank has 8 registers named R0… R7.
At a time, only of the four banks is the “active bank”.
RS1 and RS0 are used by the programmer to select the active bank.
Example 1:
32 H0011 0001
23 H0010 0011
54 H0101 0100
Example 2:
39 H0011 1001
27 H0010 0111
60 H0110 0000
Flag Affected: CY=0, AC=1, OVR=0, P=0
Example 3:
42 H0100 0010
44 H0100 0100
86 H1000 0110
Flag Affected: CY=0, AC=0, OVR=1, P=1
The result 86H is out of range for a “Signed” Number as it has become greater than
+7FH.
Such an event is called a “Signed Overflow”.
In such a case the MSB of the result gives a wrong sign.
Though the result is +ve (+86H) the MSB is “1” indicating that the result is –ve.
Overflow is determined by doing an Ex-Or between the 2nd last Carry and the last
Carry.
Here the 2nd last Carry (the one coming into the MSB) is “1”.
The final carry (The one going out of the MSB) is “0”. As “1” Ex-Or “0” = “1”, the
Overflow flag is “1”.
STACK OF 8051:
Another important element of the Internal RAM is the Stack.
Stack is a set of memory locations operating in Last in First out (LIFO) manner.
It is used to store return addresses during ISRs and also used by the
programmer to store data during programs.
In 8051, the Stack can only be present in the Internal RAM.
This is because, SP which is an 8-bit register, can only contain an 8-bit address
and External RAM has 16-bit address. (#Viva)
On reset SP gets the value 07H.
Thereafter SP is changed by every PUSH or POP operation in the following
manner:
PUSH: POP:
SP SP + 1 Data [SP]
[SP] New data SPSP – 1
The reset value of SP is 07H because, on the first PUSH, SP gets incremented
and then data is pushed on to the stack. This means the very first data will be
stored at location 08H.
This does not affect the default bank (0) and still gives the stack, the maximum
space to grow.
The programmer can relocate the stack to any desired location by simply
putting a new value into SP register.
2.6 EXPLAIN THE PORT STRUCTURE & OPERATION, TIMER/COUNTERS,
SERIAL INTERFACE& EXTERNAL MEMORY:
8051 microcontrollers have 4 I/O ports each of 8-bit, which can be configured as input
or output. Hence, total 32 input/output pins allow the microcontroller to be connected
with the peripheral devices.
Pin configuration, i.e. the pin can be configured as 1 for input and 0 for output as per
the logic state.
Input/output (I/O) pin:
All the circuits within the microcontroller must be connected to one of its pins except
P0 port because it does not have pull-up resistors built-in.
Input pin:
Logic 1 is applied to a bit of the P register. The output FE transistor is turned off and
the other pin remains connected to the power supply voltage over a pull-up resistor of
high resistance.
Port 0:
The P0 (zero) port is characterized by two functions −
When the external memory is used then the lower address byte (addresses A0A7) is
applied on it, else all bits of this port are configured as input/output.
When P0 port is configured as an output then other ports consisting of pins with built-
in pull-up resistor connected by its end to 5V power supply, the pins of this port have
this resistor left out.
If we want to write ‘0’ on pin of port 0, when ‘0’ is written to the latch, the pin is pulled
down by the lower FET. Hence the output becomes zero.
When the control is ‘1’, address/data bus controls the output driver FETs. If the
address/data bus (internal) is ‘0’, the upper FET is ‘off’ and the lower FET is ‘on’. The
output becomes ‘0’. If the address/data bus is ‘1’, the upper FET is ‘on’ and the lower
FET is ‘off’. Hence the output is ‘1’. Hence for normal address/data interfacing (for
external memory access) no pull-up resistors are required.Port-0 latch is written to
with 1’s when used for external memory access.
Port 0 structure
Port 1:
P1 is a true I/O port as it doesn’t have any alternative functions as in P0, but this port
can be configured as general I/O only. It has a built-in pull-up resistor and is
completely compatible with TTL circuits.
Port-1 dedicated only for I/O interfacing. When used as output port, not needed to
connect additional pull-up resistor like port 0.
It have provided internally pull-up resistor as shown in fig. below. The pin is pulled
up or down through internal pull-up when we want to initialize as an output port.
To use port-1 as input port, ‘1’ has to be written to the latch. In this input mode when
‘1’ is written to the pin by the external device then it read fine.
But when ‘0’ is written to the pin by the external device then the external source must
sink current due to internal pull-up.
If the external device is not able to sink the current the pin voltage may rise, leading
to a possible wrong reading.
Port 1 structure
Port 2:
Port 2 structure
Port 3:
In this port, functions are similar to other ports except that the logic 1 must be
applied to appropriate bit of the P3 register.
Following are the alternate functions of port 3:
P3.0—–RXD
P3.1—– TXD
P3.2—– INT0’
P3.3—– INT1’
P3.4—– T0
P3.5—– T1
P3.6—– WR’
P3.7—– RD’
It works as an IO port same like Port 2 as well as it can do lots of alternate work
which are discuss above. Only alternate function of port 3 makes its architecture
different than other ports.
Each pin of Port-3 can be individually programmed for I/O operation or for alternate
function. The alternate function can be activated only if the corresponding latch has
been written to '1'. To use the port as input port, '1' should be written to the latch.
This port also has internal pull-up and limited current driving capability.
Port 3 structure
Timer 1 Timer 0
C/T: (Counter/Timer)
Set (1) - Acts as Counter (Counts external frequency on T1 and T0 pin inputs).
Cleared (0) - Acts as Timer (Counts internal clock frequency, fosc/12).
TIMER MODES:
Example 1:
WAP to generate a delay of 20 µsec using internal timer-0 of 8051. After
the delay send a “1” through Port3.1. Assume Suitable Crystal Frequency
NOTE:
; Program
SOLN: MOV TMOD, TMOD(0000
#01H 0001)2 ...Timer0
Mode1
MOV TL0, #0ECH ; Load lower byte of
Count
MOV TH0, #0FFH ; Load upper byte of
Count
MOV TCON, #10H ; Program TCON
(0001 0000)2…start
Timer0
WAIT: JNB TCON.5, ; Wait for overflow
WAIT
SETB P3.1 ; Send a “1” through
Port3.1
MOV TCON, #00H ; Stop Timer0
HERE: SJMP HERE ; End of program
Example 2:
WAP to generate a Square wave of 1 KHz from the TxD pin of 8051, Q11
usingTimer1. Assume Clock Frequency of 12 MHz
NOTE:
For a Square wave of 1 KHz, the delay required is .5 msec.
We know, each count will require 1/1MHz 1 µsec.
Thus for 500 µsec, the Desired Count will be 500d 01F4H. For an
Up-Counter (Mode 1):
Count = Max Count – Desired Count + 1
Count = FFFF – 01F4 + 1
Count = FE0CH
Example 3:
NOTE:
For a Rectangular wave of 1 KHz, having 25% Duty Cycle: TON = 250 µsec; TOFF
= 750 µsec.
For TON: Desired Count = 250 d è 00FAH
Count ON = Max Count – Desired Count + 1
Count ON = FFFF – 00FA + 1
Count ON = FF06H
For TOFF: Desired Count = 750 d è 02EEH
Count OFF = Max Count – Desired Count + 1
Count OFF = FFFF – 02EE + 1
Count OFF = FD12H
NOTE:
If system frequency=12MHZ, it is clear that 1 count requires 1 msec.
In mode, we have 16-bit count.
Hence max pulses that can be desired is 216=65536
Count=max count-desired count+1=65535-65535+1=0
Thus we will get max delay if we load the count as 0000H, as it will have to “roll-
over” back to 0000H to overflow.
Hence max delay if XTAL is of 12 MHz.is 65536 µsec65.536 msec.
Similarly max delay if XTAL is of 11.0592 MHz…is 71106 µsec71.106 msec.
Example 4:
WAP to generate a delay of 1 SECOND using Timer1. Assume Clock
Frequency of 12 MHz (Popular Question in College!)
NOTE:
Max delay if XTAL is of 12 MHz … is 65536 µsec è 65.536 msec. Hence
to get a delay of 1 second, we will have to perform the counting
repeatedly in a loop.
Let’s keep the Desired Count 50000. (50 msec delay)
Now 50000d = C350H
Count = Max Count – Desired Count + 1 Count = FFFF – C350 + 1
Count = 3CB0H
We will have to perform this counting 1sec/50msec times20 times
Example 5
WAP to read the data from Port1, 10 times, each after a 1 sec delay. Store
the data from RAM locations 20H onwards. When the operation is
complete, ring an “Alarm” connected at Port3.1. Assume CLK = 12 MHz
NOTE:
As seen from the previous program, for a delay of 1 second, we have Count =
3CB0H. Counting has to be performed 20 times.
Also note that all ports of 8051 are o/p ports by default.
To program a port as i/p ports, all “1”s must be sent through it.
In this mode of communication data is transferred one bit at a time. This article
describes Interfacing of 8051 with PC to establish communication through its
serial port RS232.
Using the Serial Port:
8051 provides a transmit channel and a receive channel of serial communication.
The transmit data pin (TXD) is specified at P3.1, and the receive data pin (RXD) is at
P3.0.
The serial signals provided on these pins are TTL signal levels and must be boosted
and inverted through a suitable converter (Max232) to comply with RS232 standard.
All modes are controlled through SCON, the Serial Control register. The SCON bits
are defined as SM0, SM1, SM2, REN, TB8, RB8, TI, and RI from MSB to LSB. The
RS232 AND MAX232:
To establish communication between a controller and PC, we must use serial I/O
protocol RS-232 which was widely used in PC and several devices. PC works on RS-
232 standards which operates at a logic level of -25V to +25V. But Microcontrollers
use TTL logic which works on 0-5V is not compatible with the RS-232 voltage levels.
It a bit addressable register used to set the mode in which serial communication
takes place in the controller. The above figure shows the configuration of the SCON
register. Here is the list of functions of each bit.
BAUD RATE:
It is defined as number of bits transmitted or received per second and usually
expressed in Bits per second bps. For mode 0 and mode 2 the baud rate is
determined by means of 1/12, 1/32 or 1/64 of crystal frequency whereas for mode
1 and 3 it is determined by means of timer 1.
SBUF REGISTER:
It is an 8 bit register that holds the data needed to be transmitted or the data that is
received recently.
The serial port of 8051 is full duplex so the microcontroller can transmit and receive
data using the register simultaneously.
Example:
Interfacing of 16 K Byte of RAM and 32 K Byte of EPROM to 8051
Number of address lines required for 16 Kbyte memory is 14 lines and that of
32Kbytes of memory is 15 lines.
The connections of external memory is shown below.
The lower order address and data bus are multiplexed. De-multiplexing is done by
the latch.
Initially the address will appear in the bus and this latched at the output of latch
using ALE signal.
The output of the latch is directly connected to the lower byte address lines of the
memory.
Later data will be available in this bus. Still the latch output is address itself.
The higher byte of address bus is directly connected to the memory. The number
of lines connected depends on the memory size.
The RD and WR (both active low) signals are connected to RAM for reading and
writing the data.
PSEN of microcontroller is connected to the output enable of the ROM to read the data
from the memory.
EA (active low) pin is always grounded if we use only external memory. Otherwise,
once the program size exceeds internal memory the microcontroller will
automatically switch to external memory.
UNIT-3: 8051 ADDRESSING MODES & INSTRUCTION SET
3.1 ADDRESSING MODES OF 8051:
Addressing Modes is the manner in which operands are given in the
instruction. 8051 supports the following 5 addressing modes:
1. Immediate addressing mode
2. Register addressing mode
3. Direct addressing mode
4. Indirect addressing mode
5. Index addressing mode
Example
MOV A, 35 ; AContents of RAM location 35H
MOV A, 80H ; Acontents of port 0 (SFR at address 80H)
MOV 20H, 30H ; [20H][30H]
Example
MOVX A, @DPTR ; A [DPTR] ^
; A gets the contents of External RAM location whose address is given by DPTR.
; If DPTR=2000H, then A gets contents of location 0025H from the external
RAM
MOVX @DPTR, A ; [DPTR] ^A
; I.e. A is stored at the External RAM location whose address is given by DPTR.
Example
Based on the operation they perform, all the instructions in the 8051
Microcontroller Instruction Set are divided into five groups. They are:
Ri = Either R0 or R1
a8 = 8-bit address
rel = 8-bit signed displacement. The range is -128 to 127. It is relative to the fir
[SP]=07 //CONTENT OF SP IS 07
(DEFAULT VALUE)
MOV R6, #25H [R6]=25H //CONTENT OF R6 IS 25H
MOV R1, #12H [R1]=12H //CONTENT OF R1 IS 12H
MOV R4, [R4]=F3H //CONTENT OF R4 IS F3H
#0F3H
PUSH 6 [SP]=08 [08]=[06]=25H
//CONTENT OF 08 IS 25H
PUSH 1 [SP]=09 [09]=[01]=12H
//CONTENT OF 09 IS 12H
PUSH 4 [SP]=0A [0A]=[04]=F3H
//CONTENT OF 0A IS F3H
POP 6 [06]=[0A]=F3H [SP]=09
//CONTENT OF 06 IS F3H
POP 1 [01]=[09]=12H [SP]=08 //CONTENT OF 01 IS 12H
POP 4 [04]=[08]=25H [SP]=07 //CONTENT OF 04 IS 25H
Exchange instructions
The content of source i.e. register, direct memory or indirect memory will be
exchanged with the contents of destination i.e. accumulator.
1. XCH A,R3
2. XCH A,@R1
3. XCH A,54h
Exchange digit.
Exchange the lower order nibble of Accumulator (A0-A3) with lower order
nibble of the internal RAM location which is indirectly addressed by the
register.
1. XCHD A,@R1
2. XCHD A,@R0
2. ARITHMETIC INSTRUCTIONS:
Addition
In this group, we have instructions to
Add the contents of A with immediate data with or without carry.
1. ADD A, #45H
2. ADDC A, #OB4H
Add the contents of A with register Rn with or without carry.
1. ADD A, R5
2. ADDC A, R2
Add the contents of A with contents of memory with or without carry using
direct and indirect addressing
1. ADD A, 51H
2. ADDC A, 75H
3. ADD A, @R1
4. ADDC A, @R0
5.
CY AC and OV flags will be affected by this operation.
Subtraction
In this group, we have instructions to
Subtract the contents of A with immediate data with or without carry.
1. SUBB A, #45H
2. SUBB A, #OB4H
Subtract the contents of A with register Rn with or without carry.
1. SUBB A, R5
2. SUBB A, R2
Subtract the contents of A with contents of memory with or without carry
using direct and indirect addressing
1. SUBB A, 51H
2. SUBB A, 75H
3. SUBB A, @R1
4. SUBB A, @R0
Multiplication
MUL AB.
This instruction multiplies two 8 bit unsigned numbers which are stored
in A and B register.
After multiplication the lower byte of the result will be stored in
accumulator and higher byte of result will be stored in B register.
Examples:
MOV A,#45H ;[A]=45H
MOV B,#0F5H ;[B]=F5H
MUL AB ;[A] x [B] = 45 x F5 = 4209
;[A]=09H, [B]=42H
Division
DIV AB.
This instruction divides the 8 bit unsigned number which is stored in A by
the 8 bit unsigned number which is stored in B register.
After division the result will be stored in accumulator and remainder will
be stored in B register.
Examples:
When two BCD numbers are added, the answer is a non-BCD number.
To get the result in BCD, we use DAA instruction after the addition. DAA
works as follows.
If lower nibble is greater than 9 or auxiliary carry is 1, 6 is added
to lower nibble.
If upper nibble is greater than 9 or carry is 1, 6 is added to upper
nibble.
Examples 1:
MOV
A,#23H
MOV
R1,#55H
ADD //
A,R1 [A]=78
DA A // no changes in the accumulator after
[A]=78 DAA
Examples 2:
MOV
A,#53H
MOV
R1,#58H
ADD //
A,R1 [A]=ABH
DA A // [A] =11, C=1.
Answer is 111. Accumulator data is changed after
DAA
Increment:
Increments the operand by one.
INC A
INC Rn
INC DIRECT
INC @Ri
INC DPTR
Decrement:
Decrements the operand by one.
DEC A
DEC Rn
DEC DIRECT
DEC @Ri
The Logical Instructions, which perform logical operations like AND, OR, XOR,
NOT, Rotate, Clear and Swap.
Logical Instruction are performed on Bytes of data on a bit-by-bit basis.
Logical AND
ANL destination, source: ANL does a bitwise "AND" operation between source
and destination, leaving the resulting value in destination.
The value in source is not affected.
"AND" instruction logically AND the bits of source and destination.
ANL A, #DATA ANL A, Rn
ANL A, DIRECT ANL A, @Ri
ANL DIRECT, A ANL DIRECT, #DATA
Logical OR
Logical Ex-OR
Logical NOT
Rotate Instructions
RRA
This instruction is rotate right the accumulator.
Each bit is shifted one location to the right, with bit 0 going to bit 7.
RLA
Rotate left the accumulator. Each bit is shifted one location to the left, with bit 7
going to bit 0
RRC A
Rotate right through the carry. Each bit is shifted one location to the right, with
bit 0 going into the carry bit in the PSW, while the carry was at goes into bit 7
RLC A
Rotate left through the carry. Each bit is shifted one location to the left, with bit 7
going into the carry bit in the PSW, while the carry goes into bit 0.
As the name suggests, Boolean or Bit Manipulation Instructions will deal with bit
variables.
We know that there is a special bit-addressable area in the RAM and some of the
Special Function Registers (SFRs) are also bit addressable.
8051 has 128 bit addressable memory. Bit addressable SFRs and bit addressable
PORT pins. It is possible to perform following bit wise operations for these bit
addressable locations.
1. LOGICAL AND
a. ANL C,BIT(BIT ADDRESS) ; logically and’ carry and content of bit
address, Store result in carry
b. ANL C, /BIT; ; logically and’ carry and complement of
Content of bit address, store result in carry
2. LOGICAL OR
a. ORL C,BIT(BIT ADDRESS) ; logically or’ carry and content of bit address,
Store result in carry
b. ORL C, /BIT ; logically or’ carry and complement of
Content of bit address, store result in carry
3. CLR bit
4. CPL bit
a. CPL bit ; content of bit address specified will be complemented.
b. CPL C ; content of carry will be complemented.
It can be seen that the upper 5bits of the program counter (PC) hold the page
number and the lower 11bits of the PC hold the address within that page. Thus,
an absolute address is formed by taking page numbers of the instruction (from
the program counter) following the jump and attaching the specified 11bits to
it to form the 16-bit address.
Advantage:
The instruction length becomes 2 bytes.
Example of short absolute jump: - ACALL <address 11>
AJMP <address 11>
Applications that need to access the entire program memory from 0000H to
FFFFH use long absolute jump.
Since the absolute address has to be specified in the op-code, the instruction
length is 3 bytes (except for JMP @ A+DPTR). This jump is not re-locatable.
Example: -
1. unconditional jump:
It is a jump in which control is transferred unconditionally to the target location.
Bit level JUMP instructions will check the conditions of the bit and if
condition is true, it jumps to the address specified in the instruction. All
the bit jumps are relative jumps.
JB bit, rel ; jump if the direct bit is set to the relative address specified.
JNB bit, rel ; jump if the direct bit is clear to the relative address specified.
JBC bit, rel ; jump if the direct bit is set to the relative address specified and
then clear the bit
UNIT-4: 8051 ASSEMBLY LANGUAGE PROGRAMMING TOOLS
4.1 PROGRAM USING JUMP, LOOP AND CALL INSTRUCTION IN 8051:
Example 1:
write a program to clear Accumulator [A], then Add 5 to the accumulator 20
times:
This program adds value 3 to the Accumulator 20 times.
MOV A,#0 ;Accumulator=0, Clear Accumulator
MOV R2,#20 ;Load counter R2=20
AGAIN: ADD A,#05 ;Add 05 to Accumulator
DJNZ R2,AGAIN ;Repeat Until R2=0 [20 times]
MOV R5,A ;Save Accumulator in R5
Example 2:
Write a program to multiply 25 by 10 using the technique of repeated addition.
Solution:
Multiplication can be achieved by adding the multiplicand repeatedly, as many times
as the multiplier.
E.g. 25x10=250 (FAH)
25+25+25+25+25+25+25+25+25+25=250
MOV A,#0 ;Accumulator=0, Clear Accumulator
MOV R2,#10 ;the multiplier is placed in R2
AGAIN: ADD A,#25 ;Add the multiplicand to the Accumulator
DJNZ R2,AGAIN ;Repeat Until R2=0 (10 times)
MOV R5,A ;Save Accumulator in R5
The maximum number of times that a loop can be repeated is only 256 since the count
register R2 is an 8-bit register and can hold only numbers from 0 to 255.
Example 3:
Write a program to add the first ten natural numbers.
Solution:
The first 10 natural numbers are 1, 2, 3…10
MOV A,#0 ;Accumulator=0, Clear Accumulator
MOV R2,#10 ; Load counter value in R2
MOV R0, #0 ; initialize R0 to zero.
AGAIN: INC R0 ; increment R0 to hold the natural numbers
ADD A,R0 ;Add first number to accumulator
DJNZ R2,AGAIN ;Repeat Until R2=0 (10 times)
MOV 46H,A ;Save the result (37H)in RAM location 46H
The maximum number of times that a loop can be repeated is only 256 since the count
register R2 is an 8-bit register and can hold only numbers from 0 to 255.
The maximum count is 256. But if we want to repeat an action more times than 256,
we use a loop inside a loop, which is called nested loop. In nested loop, we use two
registers to hold the count.
Example 4:
Write a program to load the accumulator with the value 66H, and complement
the accumulator ACC 600 times.
Solution:
700 is larger than 255 [the maximum capacity of any register], we use two registers
to hold the count. We are using R2, R3 for the count.
Example 5:
MOV A,R0 ;A = R0
JZ OVER ;Jump if accumulator A = 0
MOV A,R1 ;A = R1
JZ OVER ;Jump if accumulator A = 0
.........
OVER:
OVE
Either R0 or R1 is zero, it jumps to the label OVER. The JZ instruction can be used
only for register accumulator A.
It can used only check to see whether the Accumulator is zero. It does not apply
to any other register.
Example 6:
Write a program in which if R4 register contains the value 0. Then put 55H in
R4 register.
Solution:
Example 6:
Write a program to find the sum of the values 78H, F4H and E1H. Put the sum in registers
R0 [low byte] and R5 [high byte]:
Solution:
MOV A,#0 ;Clear accumulator A=0
MOV R5,A ;Clear R5
ADD A,#78H ;Accumulator A=0+78H=78H
JNC HERE_1 ;If No carry, add next number
INC R5 ;If carry flag CY=1, increment R5
HER HERE_1:ADD A,#0F4H ;A=78H+F4=6C and carry flag CY=1,as [78H+F4=16C]
JNC HERE_2 ;Jump if Carry flag CY=0
INC R5 ;If carry flag CY=1,then increment R5, i.e. R5=1
HERE_2: ADD A,#0E1H ;A=6C+E1=4D and carry flag CY=1,as [6C+E1=14D]
JNC OVER ;Jump if carry flag CY=0
INC R5 ;If carry flag CY=1, increment R5
OVER: MOV R0,A ;Now R0=4D, and R5=02
END
Example 7:
Write a program to multiply the numbers 0ECH by 25H using the technique of
repeated addition.
Solution:
They are all 2-byte instructions. In these instructions, the first byte is the opcode and
the second byte is the relative address.
The target address is relative to the value of the program counter (PC).
To calculate the target address, the second byte is added to the PC (program counter)
of the instruction immediately below the jump.
Example 8:
WAP to verify the jump forward address calculation.
LINE PROGRAM COUNTER OPCODE MNEMONIC OPERAND
01 0000 ORG 0000
02 0000 7800 MOV R0,#01
03 0002 7455 MOV A,#66H
04 0004 6003 JZ NEXT
05 0006 08 INC R1
06 0007 04 AGAIN: INC A
07 0008 04 INC A
08 0009 2477 NEXT: ADD A,#77H
09 000B 5005 JNC OVER
10 000D E4 CLR A
11 000E F8 MOV R3,A
12 000F F9 MOV R2,A
13 0010 FA MOV R1,A
14 0011 FB MOV R0,A
15 0012 2B OVER ADD A,R3
16 0013 50F2 JNC AGAIN
17 0015 80FE SJMP HERE
18 0017
END
Answer:
The target address for a forward jump is calculated by adding the program counter (PC)
of the following instruction to the second byte of the short jump instruction, which is
called the relative address.
JZ and JNC instructions both jump forward. In line 04, the instruction "JZ NEXT" has
opcode of '60' and operand of '03' at the program counter (PC) address of '0004' and
'0005'.
The 03 is the relative address, relative to the address of the next instruction "INC R0"
at program counter address of '0006'.
By adding 0006 to 03, the target address so the label NEXT, 0009 is generated, where
the jump will take place at NEXT: ADD A, #77H.
In the same way, at line 09, the "JNC OVER instruction has opcode and operand of '50'
and '05', where '50' is the opcode and '05' is the relative address.
So 05 is added to 000D, the address if instruction "CLR A", resulting in 0012, the
address of the label OVER of mnemonic operand 'OVER ADD A, R3'.
LCALL is a 3-byte instruction. This first byte is the opcode and the second and third
bytes are used for the address for the target subroutine.
Anywhere Within the 64K byte address space of the 8051, LCALL can be used to call
subroutines.
The 8051 microcontroller knows where to come back to, it automatically saves on the
stack the address of the instruction immediately below the LCALL.
When a subroutine is called, the control is transferred to that subroutine, and the
processor saves the program counter (PC) on the stack and begins to fetch instructions
from the new location.
After finishing execution of the subroutine, the instruction RET (Return) transfers
control back to the caller.
RET (Return) needs by every subroutine as the last instruction.
Example 1:
Write a program to toggle all the bits of port 1 by sending it the values 55H and AAH
continuously. Put a time delay between each issuing of data to port 1.
Answer:
ORG 0
BACK MOV A, #55H ; load A with 55
MOV P1,A ; send 55H to port 1
LCALL DELAY ; time delay
MOV A, #0AAH ; load a with AA (in hex)
MOV P1,A ; send AAH to port 1
LCALL DELAY
SJMP BACK ; keep doing this indefinitely
; ---------- this is the delay subroutine
ORG 300H ; put time delay at address 300H
DELAY: MOV R5, #0FFH ; R5=255(FF in hex), the counter
AGAIN: DJNZ R5, AGAIN ; stay here until R5 becomes 0
RET ; return to caller ( when R5=0)
END ; end of asm file
When the first "LCALL DELAY" is executed, the address of the instruction right below
it, "MOV A, #0AAH", is pushed onto the stack, and the 8051 starts to execute
instructions at address 300H.
In the DELAY subroutine, first the counter R4 is set to 255 [FFH in hex]. 255 means the
loop will be repeated 256 times. When R4 becomes zero, control falls to the RET
instruction which pops address from the stack into the program counter and resumes
executing the instructions after the CALL.
The amount of time delay depends on the frequency of the 8051. We can increase the
time delay by using nested loop as shown below.
DELAY:
MOV R4,#255 ; nested loop delay
NEXT: MOV R5, #255 ; R4= 255(FF in hex)
AGAIN: DJNZ R5, AGAIN ;stay here until R5 becomes 0
DJNZ R4, NEXT ;decrement R4
; keep loading R5 until R4=0
RET ; return ( when R4=0 )
ORG 0
MOV A, #55H ; load A with 55H
BACK MOV P1, A ; issue value in register A to port 1
LCALL DELAY ; time delay
CPL A ; complement register A i.e.55H becomes AAH
SJMP BACK ; keep doing this indefinitely
; ---------- this is the delay subroutine DELAY:
MOV R5, #0FFH ; R5=255(FF in hex), the counter
AGAIN: DJNZ R5, AGAIN ; stay here until R5 becomes 0
RET ; return to caller (when R5=0)
END ; end of asm file
Example 2:
WAP Analyze the stack contents after the execution of the first LCALL.
When the first LCALL is executed, the address of the instruction "MOV A, #0AAH"
is saved on the stack.
The low byte goes first and the high byte is last.
The last instruction of the called instruction must be a RET instruction which
directs the CPU to POP the top bytes of the stack into the program counter (PC)
and resume executing at address 07.
The stack frame after the first LCALL is given below.
0A
09 00
08 07
Stack Pointer= 09
Example 2:
WAP analyze the stack for the first LCALL instruction.
01 0000 ORG 0
02 0000 7455 BACK: MOV A, #55H ; load A with 55H
03 0002 F590 MOV P1, A ; send 55H to port 1
04 0004 7C99 MOV R4, #99H
05 0006 7D67 MOV R5, #67H
06 0008 120300 LCALL DELAY ; time delay
07 000B 74AA MOV A, #0AAH ; load A with AA
08 000D F590 MOV P1, A ; send AAH to port 1
09 000F 120300 LCALL DELAY
10 0012 80EC SJMP BACK ; keep doing this
11 0014 ;---------------- this is the delay subroutine
12 0300 ORG 300H
13 0300 C004 DELAY: PUSH 4 ; PUSH R4
14 0302 C005 PUSH 5 ; PUSH R5
15 0304 7CFF MOV R4, #0FFH ; R4=FFH ;
16 0306 7DFF NEXT: MOV R5, #0FFH ; R5=255H ;
17 0308 DDFE AGAIN: DJNZ R5 AGAIN ; stay here
18 030A DCFA DJNZ R4, NEXT
19 030C D005 POP 5 ; POP into R5
20 030E D004 POP 4 ; POP into R4
21 0310 22 RET ; return to caller
22 END ; end of asm file
Answer:
First notice that for the PUSH and POP instructions we must specify the direct address
of the register being pushed or popped. Here is the stack frame.
CALLING SUBROUTINES:
In assembly language programming it is common to have one main program and
many subroutines that are called from the main program.
This allow us to make each subroutine into a separate module.
Each module can be tested separately and then brought together with the main
program.
More importantly, in a large program the modules can be assigned to different
programmers in order to shorten development time.
It needs to be emphasized that in using LCALL, the target address of the subroutine
can be anywhere within the 64K-byte memory space of the 8051.this is not the
case for other instructions.
The CPU takes a certain number of clock cycles to execute an instruction. These
clock cycles are referred to as machine cycles.
The length of the machine cycle depends on the frequency of the crystal oscillator
connected to the 8051 system.
The crystal oscillator, along with the on-chip circuitry, provide the clock source
for the 8051 CPU.
The crystal oscillator frequency can vary from 4MHz to 30MHz.
To make the 8051 system compatible with the serial port of the personal computer
PC, 11.0592MHz crystal oscillators is used.
In the 8051, one machine cycle lasts 12 oscillator periods.
So to calculate the machine cycle, we take 1/12 of the crystal frequency, then take
the inverse of it results in time period i.e. frequency = 1/time period.
Example 1:
To find the time period of the machine cycle in each case for the following crystal
frequency of different 8051 based systems: 11.0592 MHz, 16 MHz, and 20 MHz
Answer:
11.0592 MHz:
11.0592/12 = 921.6 KHz
Machine cycle = 1/921.6 KHz = 1.085µs
16 MHz:
16MHz/12 = 1.333 MHz
Machine cycle = 1/1.333 MHz = 0.75µs
20MHz:
20MHz/12 = 1.66 MHz
Machine Cycle = 1/1.66 MHz = 0.60µs
Example 2:
To find how long it takes to execute each of the following instructions, for a crystal
frequency of 11.0592 MHz The machine cycle of a system of 11.0592 MHz is 1.085 µs.
Example 3:
To find the size of the delay if the crystal frequency of 11.0592 MHz is
connected.
Example 4:
To find the time delay for the following subroutine with 11.0592 MHz crystal
frequency is connected to the 8051 system.
The time delay inside the HERE loop is [255(1+1+1+1+2)] x 1.085 us = 1660.05µs
The time delay of the two instructions outside the loop is:
There are four ports in 8051 microcontroller named as P0, P1, P2 and P3.
Each port has 8 pins. For Port 0 8 pins names as P0.0, P0.1, P0.2, P0.3, P0.4, P0.5,
P0.6, and P0.7.
All the ports upon RESET are ready to be configured or used as output.
To use all these ports as an input port, it must be programmed.
PORT 0:
Port 0 has 8 pins P0.0, P0.1, P0.2, P0.3, P0.4, P0.5, P0.6, and P0.7.
This port can be used for input or output.
Each pin of the port 0 must be connected externally to a 10K Ohm pull-up resistor,
to use Port 0 as both input or output ports.
This is because the Port 0 (P0) is an open drain.
This is not the case in other ports P1, P2 and P3. 'Open drain' is a term used for
MOS chips, as 'open collector' is used for TTL chips.
To use Port 0 for both input and output, have to connect Port 0 to pull-up resistors.
When external pull-up resistors connected upon reset, Port 0 is configures as
output port.
Role of Port 0 as Input Port:
To make Port 0 as input port, the pull up resistors are connected to port 0.
The port must be programmed by writing 1 to all the bits.
Let’s examine the code example below in which the Port 0 is configured first as an
input port by writing 1's to it and then data is received from that port and send to
Port 1 (P1).
PORT 1:
Port 1 has a total of 8 pins. P1.0, P1.1, P1.2, P.13, P1.4, P1.5, P1.6, and P1.7.
Port 1 can be used as an input or output.
As compares to Port 0, this port does not need any pull-up resistors.
Port 1 already has internally connected pull-up resistors.
Port 1 is configured as an output port when reset.
Example 1:
Let’s examine the code, which will continuously send Output to Port 1 the alternating
values 55H and AAH.
The Port 1 is configures as input port by writing 1's to it, then data is received from
that port and saved in R7, R6 and R5.
PORT 2:
Port 2 also has total of 8 pins. P2.0, P2.1, P2.2, P2.3, P2.4, P2.5, P2.6, and P2.7.
Port 2 can be used for input or output port.
To make Port 2 as an input, the Port 2 must be programmed by writing 1's to all
bits.
Example 3:
The code will send out continuously to Port 2 an alternating values 55H and AAH to
toggle the bits or Port 2 continuously.
MOV A, #55H
BACK: MOV P2, A
ACALL DELAY
CPL A ; complement register A
SJMP BACK
Example 4:
The Port 2 is configures as input port by writing all 1's, then data is received from that
port and is sent to Port 1 continuously.
PORT 3:
Port 3 has total 8 Pins. P3.0, P3.1, P3.2, P3.3, P3.4, P3.5, P3.6, and P3.7.
Port 3 can be sued as an input port or output port.
Port 3 does need any pull-up resisters, just like the Port 1 and Port 2 does not
require pull-up resistors.
Only Port 0 require Pull-up resistors.
Port 3 configured as an output port upon system reset.
Port 3 has additional function of providing signals of interrupts.
Example 1:
Let’s examine an example in which the entire 8 bits of Port 1 data are accessed.
Example 2:
MOV P1, #55H ; Load Port 1 with 55H or 01010101
in Binary
AGAIN: XRL P1, #0FFH ; EX-OR Port 1 with 1111 1111
Example 3:
Let’s examine the code in which the code toggles the Port bit P1.3 continuously.
BACK: CPL P1.3 ; Complement Port 1 bit 3 i.e. P1.3
ACALL DELAY ; wait
SJMP BACK ; go back to instruction first instruction again
P0 P1 P2 P3 PORT BIT
P0.0 P1.0 P2.0 P3.0 D0
P0.1 P1.1 P2.1 P3.1 D1
P0.2 P1.2 P2.2 P3.2 D2
P0.3 P1.3 P2.3 P3.3 D3
P0.4 P1.4 P2.4 P3.4 D4
P0.5 P1.5 P2.5 P3.5 D5
P0.6 P1.6 P2.6 P3.6 D6
P0.7 P1.7 P2.7 P3.7 D7
The instruction "JNB P1.3,AGAIN", mean jumps to the target 'AGAIN' if no bit is
set or if bit P1.3 is low, and stays in the loop as long as P1.3 becomes low.
When P1.3 becomes high, it gets out of the loop, writes 55H to Port 1, and creates
a High-to-Low pulse by the sequence of instructions SETB and CLR.
The destination register accumulator contains 00. The following flags are
affected:
Carry Flag CY = 1 Out from D7, there is a carry
Parity Flag PF = 1 An even number of once is zero
Auxiliary Carry AC = 0 No carry from D3 to D4
Example 2:
Let’s assume that the RAM locations 30H to 44H have some values given below. The
code program will find the sum of the values. When the program ends, the register A
should contain the low byte and R2 contain the high byte.
In the second iteration of the loop, 9CH is added to the accumulator register A by
the instruction "AGAIN: ADD A, @R0".
The accumulator already contains value 8AH which is added to the value 9CH i.e.
A=9C+8AH=26H.
The carry flag is set to 1 i.e. CY=1 and R5 cannot be skipped in this case and R5 is
incremented by 1 i.e. R5=01 by the instruction "INC R5", and the counter
decrement by 1 value again, and jump to the label 'AGAIN' by the instruction "DJNZ
R3,AGAIN" i.e. R3=03.
When R0=32H and R3=3, Carry flag=0:
In the third iteration of the loop, 3EH is added to the accumulator register A by the
instruction "AGAIN: ADD A, @R0".
The accumulator already contains value 26H which is added to the value 3EH i.e.
A=26+3EH=64H.
The carry flag is set to 0 i.e. CY=0 and R5 is skipped in this case and R5 is not
incremented by 1, and the counter decrement by 1 value again, and jump to the
label 'AGAIN' by the instruction "DJNZ R3,AGAIN" i.e. R3=02.
When R0=33H and R3=2, Carry flag=1:
In the fourth iteration of the loop, 9DH is added to the accumulator register A by
the instruction "AGAIN: ADD A, @R0".
The accumulator already contains value 64H which is added to the value 9DH i.e.
A=64H+9DH=01H.
The carry flag is set to 1 again. i.e. CY=1 and R5 cannot be skipped in this case and
R5 is incremented by 1 again i.e. R5=02 by the instruction "INC R5", and the
counter decrement by 1 value again, and jump to the label 'AGAIN' by the
instruction "DJNZ R3,AGAIN" i.e. R3=01.
When R0=34H and R3=1, Carry flag=1:
In the fifth iteration of the loop, FFH is added to the accumulator register A by the
instruction "AGAIN: ADD A, @R0".
The accumulator already contains value 01H which is added to the value FFH i.e.
A=01H+FFH=00H.
The carry flag once again is set to 1. i.e. CY=1 and R5 cannot be skipped in this case
and R5 is incremented by 1 i.e. R5=03 by the instruction "INC R5", So, the total
accumulated carry becomes 03, as the carry occurs total of three times in this
program.
The counter is decrement by 1 value again, by the instruction "DJNZ R3, AGAIN"
i.e. R3=00.
This time it cannot jump to the label 'AGAIN' as R3=0, DJNZ as it is zero so the
condition becomes false and it comes out from the loop.
The program is end. When the loop is finished, the sum is held by the accumulator
registers A and R5.
The accumulator register has low byte saved while the R5 has high byte saved.
ADDITION OF 16-BIT NUMBERS & ADDC INSTRUCTION:
The ADDC instruction means addition with carry. The ADDC instruction is used when
two 16-bit data operands are need to be added and the propagation of a carry from
the lower byte to the higher byte.
Example 3:
Let’s add the two 16 bit numbers:
Carry 1
2B D6
+ 2A 7C
56 52
In the example above, when the first byte D6+7C is added, we get the result
D6+7C=152.
Then due to carry flag originally we get D6+7C=52. "1" of "152" will go to the
higher byte as a carry.
The carry flag CY=1. The carry is propagated to the higher byte then we have
1+2B+2A=56.
All the values are in hex. i.e. 1H+2BH+2AH=56H.
Example 4:
Let’s add two 16 bit numbers. First number is 2DF6H and 4C9DH. Put the sum in
R5 and R4. R5 for higher byte and R4 for lower byte.
ADDC A, #4CH ; Add with carry, the high byte in the accumulator
; 2DH with another high byte 4CH and place the
; result back in accumulator i.e. A=1+2D+2C= 7A.
; All values are in Hex.
MOV R5, A ; Save the result of high bytes, sum of addition in
; R5 register
Example:
Show the steps involved in the following.
CLR C ; make CY=0
MOV A, #3FH ; load 3FH into A (A=3FH)
MOV R3, #23H ; load 23H into R3 (R3=3FH)
SUBB A, R3 ; subtract A-R3, place result in A
Solution:
A= 3F 0011 1111 0011 1111
R3=23 0010 0011 + 1101 1101 (2’s complement)
1C 1 0001 1100
0 CF=0 (step 3)
The flag would be set as follows: CY=0, AC=0 and the programmer must look at the
carry flag to determine if the result is positive or negative.
Example:
CLR C
MOV A, #4CH ; load A with value 4CH (A=4CH)
SUBB A, #6EH ; subtract 6E from A
JNC NEXT ; if CY=0 jump to NEXT target
CPL A ; if CY=1 then take 1’s complement
INC A ; and increment to get 2’s complement
NEXT: MOV R1, A ; save A in R1
Solution:
Following are the steps for “SUBB A, #6EH:
Example:
CLR C ; CY=0
MOV A, #62H ; load A with value 62H (A=62H)
SUBB A, #96H ; 62H – 96H=CCH with CY=1
MOV R7, A ; save the result
MOV A, #27H ; A=27H
SUBB A, #12 ; 27H-12H-1=14H
MOV R6, A ; save the result
Solution:
After the SUBB, A=62H-96H=CCH and the carry flag is set high indicating there is
a borrow.
Since CY=1, when SUBB is executed the second time A=27H-12H-1=14H.
Therefore, we have 2762H-1296H=14CCH.
Example:
In a semester, a student has to take six courses. The marks of the student (out of 25)
are stored in RAM locations 47H onwards. Find the average marks, and output it on
port 1.
Solution:
MOV R1, #06 ; R1 stores the number of courses
MOV B, #06 ; only B can be used as the divisor register
MOV R0, #47H ; R0 acts as the pointer to the data
MOV A, #0 ; Clear A
BACK: ADD A,@R0 ; add the data to the A register
INC R0 ; increment the pointer
DJNZ R1, BACK ; repeat addition until R1=0
DIV AB ; divide the sum by 6 to get the average
; The quotient is in A, remainder in B
MOV P1, A ; ignore the remainder, output the average
Positive number:
The range of positive number that can be represented by the format shown in
figure below is 0 to +127.
If a positive number is larger than +127, a 16-bit size operand must be used.
Since the 8051 doesn’t support 16-bit data.
Negative number:
For negative numbersD7 is 1; however the magnitude is represented in its 2’s
complement.
Convert to negative number representation (2’s complement), follows these
three steps:
1. Write the magnitude of the numbers in 8-bit binary (no sign).
2. Invert each bit.
3. Add 1 to it.
Example 1:
-7
1. 0000 0111
2. 1111 1000
3. 1111 1001
4. F9H ; representation in hex
Example 2:
-56
1. 0011 1000
2. 1100 0111
3. 1100 1000
4. C8H ; representation in hex
AND:
ANL destination, source ; dest=dest AND source
This instruction will perform a logical AND on the two operands and place the
result in the destination.
The destination is normally the accumulator.
Example:
Solution:
35H 0011 0101
0FH 0000 1111
05H 0000 0101 35H AND 0FH= 05H
OR:
ORL destination, source; dest=dest OR source
The destination and source operands are ORed, and the result is placed in the
destination.
Example:
MOV A, #04H ; A=04H
ANL A, #30H ; A = A OR 30H (now A=43H)
Solution:
04H 0000 0100
30H 0011 0000
34H 0011 0100 04H OR 30H= 34H
XOR:
XRL destination, source ; dest = dest XOR source
This instruction will perform a XOR operation on the two operands and place the
result in the destination.
The destination is normally the accumulator.
Example 1:
Solution:
54H 0101 0100
78H 0111 1000
2CH 0010 1100 54H OR 78H= 2CH
Example 2:
Read and test P1 to see whether it has the value 45H. If it does, send 99H to P2.
Example:
Find the 2’s complement of the value 85H.
Solution:
MOV A, #85H
CPL A ; 1’s complement
ADD A, #1 ; 2’s complement
COMPARE INSTRUCTION:
The 8051 has an instruction for the compare operation.it has the following
syntax
CJNE destination, source, relative index
In the 8051, the action of comparing and jumping are combined into a single
instruction called CJNE (compare and jump if not equal)
The CJNE instruction compare two operands, and jumps if they are not equal.
In addition, it changes the CY flag to indicate if the destination operand is larger
or smaller.
The operand always remain unchanged.
For example: after the execution of the instruction “CJNE A, NEXT”, register A
still has its original value.
This instruction compares register A with value 67H and jump to the target
address NEXT only if register A has a value other than 67H
Example
MOV A, #55H
CNJE, A, #99H, NEXT
………
………..
NEXT:
Solution:
a) Yes, it jumps because 55H 99H are not equal.
b) A=55H, its original value before the comparison.
Example 1:
10 hex number are stored in ram location 50H onwards. Write a program to find the
biggest number in the set. The biggest number should finally be saved in 60H.
Solution:
Example 2:
Assume that P1 is an input port connected to a temperature sensor. Write a program
to read the temperature and test it for the value 75. Accordingly to the test results,
place the temperature value into the registers indicated by the following.
If T=75 then A=75
If T<75 then R1=T
If T>75 then R2=T
Solution:
Example 3:
Assume internal RAM memory location 40H-44H contain daily temperature for five
days, as shown below. Search to see if any of the values equals 65. If value 65 does
exists in the table, give its location R4, otherwise make R4=0
40H= (76) 41H=(79) 42H=(69) 43H=(65) 44H=(62)
Solution:
MOV R4, #0H ; R4=0
MOV R0, #40 ; load pointer
MOV R2, #05 ; load counter
MOV A, #65 ; move a number to A
BACK: CJNE A, @R0, NEXT ; compare with B
MOV R4, R0 ; if 65 save address
SJMP EXIT ; and exit
NEXT: INC R0 ; otherwise increment pointer
DJNZ R2, BACK ; keep checking until count=0
EXIT …..
Example 4:
Write a program to check if the character string of length 7, stored in RAM locations
50H onwards is a palindrome. If it is, output ‘Y’ to P1
Solution:
MOV R2, #03H ; take half the string length as a counter value
MOV R0, #50H ; take R0 as pointer to the forward reading
MOV R1, #56h ; take R1 as pointer for the backward
; Reading of the string
BACK: MOV A, @R0 ; move into A the character pointed by R0
MOV B, @R1 ; move into B the character pointed by R1
CJNE A, B, NEXT ; compare it with the character pointed by R1
INC R0 ; increment the forward counter
DEC R1 ; decrement the backward counter
DJNZ R2, BACK ; repeat until all the character are compared
MOV P1, # ‘Y’ ; since the string is a palindrome, output ‘Y’
NEXT: NOP ; if not equal, do nothing since it is not a
; Palindrome
END
ROTATE:
It is a logical operation of 8085 microprocessor. It is a 1 byte instruction.
This instruction does not require any operand after the opcode.
It operates the content of accumulator and the result is also stored in the
accumulator.
The Rotate instruction is used to rotating the bits of accumulator.
RR A; rotate right A
Example:
RL A ; rotate left A
Example:
SWAP:
The SWAP instruction exchanges the low-order and high-order nibbles within the
accumulator. No flags are affected by this instruction.
See Also: XCH, XCHD
SWAP A
Example:
Register A= 5EH (original value) after SWAP Register A=E5H
ASCII numbers:
On ASCII keyboards, when the key ‘0’ is activated, “011 0000” (30H) is provided
to the computer. Similarly, 31H (011 0001) is provided for the key “1” and so on.
ASCII is standard in the United State (and many other country), BCD numbers are
universal.
Since the keyboard, printers and monitors all use ASCII
Example 1:
Assume that register A has packed BCD. Write a program to convert packed BCD to
two ASCB number and place them in R2 and R6.
Solution:
MOV A, #29H ; A=29H, packed BCD
MOV R2, A ; keep a copy of BCD data in R2
ANL A, #0FH ; mark the upper nibble (A=09)
ORL A, #30H ; make it an ASCII, A = 39H (‘9’)
MOV R6, A ; save it (R6=39H ASCII char)
MOV A, R2 ; A=29H, get the original data
ANL A, #0F0H ; mask the lower nibble (A=20)
RR A ; rotate right
RR A ; rotate right
RR A ; rotate right
RR A ; rotate right, (A=02)
ORL A, #30H ; A=32H, ASCII char ‘2’
MOV R2, A ; save ASCII char in R2
Of course, in the above code we can replace all the RR instructions with a single “swap
A” instruction.
Key ACII Unpacked BCD Packed BCD
4 34 0000 0100
7 37 0000 0111 01000111 or 47H
After this conversion, the packed BCD numbers are processed and he result will be in
packed BCD format. A special instruction, “DAA’, requires that data be in packed BCD
format.
Using a look-up table for ASCII:
In some applications it is much easier to use a look-up table to get the ASCII
character we need.
This is a widening used concept in interfacing a keyboard to the microcontroller.
This is shown in Example 6-35.
Example 2:
Assume that the lower three bits of PI are connected to three switched. Write a
program to send the following ASCII characters to P2 based on the status of the
switches.
000 ‘0’
000 ‘1’
000 ‘2’
011 ‘3’
100 ‘4’
101 ‘5’
110 ‘6’
111 ‘7’
Solution:
MOV DPTR, #MYTABLE
MOV A, P1 ; get 0W status
ANL A, #07H ; mask all but lower & bits
MOVC A, #A+DPTR ; get the data from look-up-table
MOV P2, A ; display value
SJMP $ ; stay here
; ----------------------------------------------------
ORG 400H
MYTABLE DB ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’ , ‘6’, ‘7’
END
Binary (hex) to ASCII conversion:
Many ADC (analog-to –digital converter) chips provide output data in binary
(hex).
To display the data on an LCD or PC screen, we need to convert it to ASCII.
The following code shows the binary – to – ASCII conversion program.
Notice that the subroutine gets a byte of 8 – bit binary (hex) data from P1 and
converts it to decimal digits, and 2nd subroutine converts the decimal digits to
ASCII digits and save them.
The low digit are saved in the lower address location and the high digit in the
higher address location.
This is referred to as the little–Endian convention that is low-byte to low-location
and high-byte to high- location.
Binary to ASCII Conversion Program:
Example 3:
; CONVERTING BIN (HEX) TO ASCII
Example 1:
WAP for the addition of 8-bit numbers located in two memory addresses.
JNC SAVE
Example 2:
To find the size of the delay if the crystal frequency of 11.0592 MHz is
connected.
The time delay inside the HERE loop is [255(1+1+1+1+2)] x 1.085 us = 1660.05µs
The time delay of the two instructions outside the loop is:
Example 1:
8051 assembly level program to create a square wave of different duty cycle.
Solution:
ORG 0000H
MOV TMOD, #01H
UP: SETB P3.2
LCALL DELAY
SJMP UP
DELAY:
MOV TH0, #0FEH
MOV TL0, #0CH
CLR TF0
SETB TR0
HERE: JNB TF0, HERE
RET
END
Example 2:
The period of the square wave is T = 1/ (2 kHz) = 500 µs. Each half pulse = 250
µs. The value n for 250 s is: 250 µs /1 µs = 250
65536 - 250 = FF06H.
TL = 06H and TH = 0FFH.
; High, Low
CLR TF1 ; Clear timer flag 1
SJMP AGAIN ; Reload timer
PROGRAMS
Example 1:
Write an 8051 program to send values 00 – FF to port P1.
Solution:
#include <reg51.h>
Void main (void)
{
Unsigned char z;
for (z = 0; z<= 255; z++)
P1 = z;
}
Example 2:
Write an 8051 C program to send hex values for ASCII characters of 0, 1, 2, 3, 4, 5, A,
B, C, & D to port P1.
Solution:
#include <reg51.h>
Void main (void)
{
Unsigned char mynum [] = “012345ABCD”;
Unsigned char z;
for (z=0; z<=10; z++
for (z = 0; z<= 10; z++)
P1 = mynum [z];
}
Example 3:
Write an 8051 C program to toggle all the bits of P1 continuously.
Solution:
// Toggle P1 forever
#include <reg51.h>
Void main (void)
{
for (; ;) //repeat forever
{
P1 = 0x55; //0x indicates the data is in hex (binary)
P1 = 0x AA;
}
}
Signed int:
Signal int is a 16 – bit data type that uses the most significant bit (D15 of D15 – D0) to
represent the – or + value a result , we have only 15 – bits for the magnitude of the
number or values from -32,768 to +32,767.
Sbit (single bit):
The Sbit keyword is a widely used 8051 C data type designed specifically to access
single- bit addressable registers. It allows access to the single bits of the SFR
registers.
Among the SFRs that are widely used & are also bit – addressable are ports P0 –
P3. Sbit can used to access individual bits of the ports
Example 4:
Write an 8051 C program to send values of -4 to +4 to port P1.
Solution:
//sign numbers
#include <reg51.h>
Void main (void)
{
char mynum[]= { +1, -1, +2, -2, +3, -3, +4, -4};
Unsigned char z;
for (z = 0; z<= 8; z++)
P1 = mynum [z];
}
Example 5:
Write an 8051 C program to toggle bit D0 of the port P1 (P1.0) 50,000 times.
Solution:
#include <reg51.h>
Sbit MYBIT = P1^0; //notice that Sbit is
//declared outside of main
Void main (void)
{
Unsigned int z;
for (z = 0; z<= 50000; z++)
{
MYBIT = 0;
MYBIT = 1;
}
}
Example 6:
Write an 8051 C Program to toggle bits of P1 continuously forever with some
delay.
Solutions:
// Toggle P1 forever with some delay in between ‘on’ and ‘off’.
#include <reg51.h>
Void main (void)
{
Unsigned int x;
for (; ;) //repeat forever
{
P1 = 0x55;
for (x = 0; x<40000; x++); //delay forever
P1=0xAA;
For (x = 0; x=40000; x++);
}
}
Example 7:
Write an 8051 program to toggle the bits of P1 ports continuously with a 250
ms delay.
Solution:
The program below is tested for the DS89C420 with XTAL = 11.0592 MHz
#include <reg51.h>
Void MSDeLay (unsigned int);
Void main (void)
{
While (1) // repeat forever
{
P1 = 0x55;
MSDelay (250);
P1 = 0xAA;
MSDelay (250);
}
}
Void MSDelay (unsigned int itime)
{
Unsigned int i, j;
for ( i = 0 ; i<itime ; i++)
for (j=0 ; j<1275 ; j++i );
}
Example 8:
Write an 8051 C program to toggle all the bits of P0 and P2 continuously with a
250ms delay.
Solution:
//This program is tested for the DS89C420 with XTAL =11.059 MHz
#include <reg51.h>
Void MSDelay (unsigned int);
Void main (void)
{
While (1) // another way to do it forever
{
P0 = 0x55;
P2 = 0x55;
MSDelay (250);
}
}
Void MSDelay (unsigned int itime)
{
Unsigned int i, j;
for (i=0 ; i<itime; i++)
for (j = 0; j<1275 ; j++) ;
}
4.6 TIMER PROGRAMMING:
8051 has 2, 16-bit Up Counters T1 and T0.
If the counter counts internal clock pulses it is known as timer.
If it counts external clock pulses it is known as counter.
Each counter is divided into 2, 8-bit registers TH1 - TL1 and TH0 - TL0.
The timer action is controlled mainly by the TCON and the TMOD registers.
Example 1:
WAP to generate a delay of 20 µsec using internal timer-0 of 8051. After
the delay send a “1” through Port3.1. Assume Suitable Crystal Frequency
NOTE: In 8051, if we select a Crystal of 12 MHz, then Timer freq will be fosc/12 è 1MHz.
Hence each count will require 1/1MHz è 1 µsec. Thus for 20 µsec, the Desired
Count will be 20 14H. For an Up-Counter (Mode 1):
Count = Max Count – Desired Count + 1 Count = FFFF – 14 + 1
Count = FFECH #Please refer Bharat Sir's Lecture Notes for this...
NOTE: For a Square wave of 1 KHz, the delay required is .5 msec.We know, each
count will require 1/1MHz è 1 µsec.
Thus for 500 µsec, the Desired Count will be 500d è 01F4H. For an Up-Counter
(Mode 1):
Count = Max Count – Desired Count + 1
Count = FFFF – 01F4 + 1
Count = FE0CH
Example 3:
WAP to generate a Rectangular wave of 1 KHz, having a 25% Duty Cycle
from the TxD pin of 8051, using Timer1. Assume XTAL of 12 MHz
NOTE: For a Rectangular wave of 1 KHz, having 25% Duty Cycle: TON = 250 µsec; TOFF =
750 µsec.
ORG 0000H
RPT: MOV TMOD, #15H ; timer 1 as timer &timer 0 as counter
SETB P3.4 ; make port P3.4 an input port
MOV TL0, #00 ; clear TL0
MOV TH0, #00 ; clear TH0
SETB TR0 ; start counter
MOV R0, #28 ; R0 = 28, time 1 second
AGAIN: MOV TL1, #00H ; TL1 = 0
MOV TH1, #00H ; TH1 = 0
SETB TR1 ; start timer 1
BACK: JNB TF1, BACK ; test timer 1 flag
CLR TF1 ; clear timer 1 flag
CLR TR1 ; stop timer 1
DJNZ R0, AGAIN ; repeat the loop until R0 = 0
Example 2:
Assume that a 1- Hz frequency pulse is connected to input pin 3.4. Write a program
to display counter 0 on an LCD. Set the initial value of TH0 to -60.
Solution:
To display the TL count on an LCD, we must convert 8-bit binary data to ASCII.
ACALL LCD _ SET _ UP ; initialize the LCD
MOV TMOD, #00000110B ; counter 0, mode 2, C/T = 1
MOV THO, #-60 ; counting 60 pulses
SETB P3.4 ; make T0 as input
AGAIN: SETB TR0 ; starts the counter
BACK: MOV A, TL0 ; get copy of count TL0
ACALL CONV ; convert in R2, R3, R4
ACALL DISPLAY ; display on LCD
JNB TF0, BACK ; loop if TF0 = 0
CLR TR0 ; stop the counter 0
CLR TF0 ; make TF0 = 0
; converting 8-bit binary to ASCII
; Upon return, R4, R3, R2 have ASCII data (R2 has LSD)
8051
P1
To LCD
P3.4
1 Hz clock T0
Solution:
#include <reg51.h>
Void T0DeLay (unsigned int);
Void main (void)
{
While (1) // repeat forever
{
P1 = 0x55;
T0Delay (250);
P1 = 0xAA;
T0Delay ();
}
}
Void T0Delay ()
{
TMOD=0x01; // Timer 0, mode 1
TL0=0x00; // load TL0
TH0=0x35; // load TH0
TR0=1; // turn on T0
While (TF0==0); // wait for TF0 to roll over
TR0=0; // turn off T0
TF0=0; // clear TF0
}
FFFFH-3500H=CAFFH=51967+1=51968
51968 x 1.085µs=56.384 ms is the approximate delay.
Timers 0 & 1 delay using mode 1 (16-bit non-auto-reload):
Example 1:
Write an 8051 C program to toggle only bit P1.5 continuously every 50ms. Use
Timer 0, mode1 (16-bit) to create the delay.
Solution:
#include <reg51.h>
Void T0MDelay (void):
Sbit mybit = P1^5;
Void main (void)
{
While (1)
{
mybit= ̴mybit; // toggle P1.5
T0M1Delay (); // Timer 0, mode 1 (16-bit)
}
}
Tested for AT89C51, XTAL=11.0592 MHz, using the Proview 32 compiler.
Void T0M1Delay (void)
{
TMOD=0x01; // Timer 0, mode 1 (16-bit)
TMOD=0xFD; // load TL0
TMOD=0x4B; // load TH0
TR0=1; // turn on T0
While (TF0==0); // wait for TF0 to roll over
TR0=0; // turn off T0
TF0=0; // clear TF0
}
Example 2:
Write an 8051 C program to toggle all bits of P2 continuously every 500ms. Use
Timer 1, mode1 to create the delay.
Solution:
// tested for DS89C420, XTAL=11.0592 MHz, using the Proview 32 compiler.
#include <reg51.h>
Void T1MDelay (void):
Void main (void)
{
Unsigned char x;
P2=0x55;
While (1)
{
P2= P
̴ 2;
For (x=0; x<=20; x++)
T1M1Delay ();
}
}
Void T1M1Delay (void)
{
TMOD=0x10; // Timer 1, mode 1 (16-bit)
TL1=0xFE; // load TL1
TH1=0xA5; // load TH1
TR1=1; // turn on T1
While (TF1==0); // wait for TF1 to roll over
TR1=0; // turn off T1
TF1=0; // clear TF1
}
A5FEH=42494 in decimal
65536-42494=23042
23042x 1.085µs=25ms and 20x 25 ms=500ms
Solution:
// tested for DS89C420, XTAL=11.0592 MHz, using the Proview 32 compiler.
#include <reg51.h>
Void T0M2Delay (void):
Sbit mybit = P1^5;
Void main (void)
{
Unsigned char x, y;
While (1)
{
mybit= ̴mybit; // toggle P1.5
for (x=0; x=250; x++) // due to for loop overhead
for (y=0; y=36; y++) // we put 36 and not 40
T0M2Delay ();
}
}
Void T0M2Delay (void)
{
TMOD=0x02; // Timer 0, mode 2 (8-bit auto-related)
TH0=-23; // load TH0 (auto-reload value)
TR0=1; // turn on T0
While (TF0==0); // wait for TF0 to roll over
TR0=0; // turn off T0
TF0=0; // clear TF0
}
256-23=233
23x1.085 µs=25 µs
25 µs x 250 x 40=250 ms by calculation.
However, the scope output does not give us this result. This is due to
overhead of the ‘for loop’ in C. to correct this problem, put 36 instead of 40.
Example 2:
Write an 8051 C program to toggle only bit P1.5 continuously every 250ms. Use
Timer 0, mode2 (8-bit auto-reload) to create the delay.
Solution:
// tested for DS89C420, XTAL=11.0592 MHz, using the Proview 32 compiler.
#include <reg51.h>
Void T1M2Delay (void):
Sbit mybit = P2^7;
Void main (void)
{
Unsigned char x;
While (1)
{
mybit= ̴mybit; // toggle P2.7
T1M2Delay ();
}
}
Void T1M2Delay (void)
{
TMOD=0x20; // Timer 1, mode 2 (8-bit auto-related)
TH1=-184; // load TH1 (auto-reload value)
TR1=1; // turn on T1
While (TF1==0); // wait for TF1 to roll over
TR1=0; // turn off T1
TF1=0; // clear TF1
}
1/2500=400 µs
400 µs/2=200 µs
200 µs/1.085 µs=184