MC Notes
MC Notes
MC Notes
PREPARED BY
E.N. SRIVANI
ASSISTANT PROFESSOR
DEPARTMENTOF ECE
SJC INSISTITUTE OF TECHNOLOGY, CHCIKBALLAPUR
Module –
1
8051 Microcontroller
Microprocessor vs Microcontroller
• General-purpose microprocessors
• Must add RAM, ROM, I/O ports, and timers externally to make them functional
• Have the advantage of versatility on the amount of RAM, ROM, and I/O ports
• Microcontroller
• 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
Microprocessor Microcontroller
Microprocessor contains ALU, General purpose Microcontroller contains the circuitry of microprocessor,
registers, stack pointer, program counter, clock and in addition it has built in ROM, RAM, I/O Devices,
timing circuit, interrupt circuit Timers/Counters
etc.
It has many instructions to move data between It has few instructions to move data between
memory and CPU 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 code Separate memory map for data and code
(program) (program)
Access time for memory and IO are more Less access time for built in memory and IO.
Microprocessor based system requires It requires less additional hardware
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 flexible Limited number of instructions with few
addressing modes addressing modes
M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R
8051 Architecture
8051 has 4 K Bytes of internal ROM. The address space is from 0000 to 0FFFh. If the
program size is more than 4 K Bytes 8051 will fetch the code automatically from external
memory.
Accumulator is an 8 bit register widely used for all arithmetic and logical operations. Accumulator
is also used to transfer data between external memory. B register is used along with Accumulator
for multiplication and division. A and B registers together is also called MATH registers.
PSW (Program Status Word). This is an 8 bit register which contains the arithmetic status of ALU
and the bank select bits of register banks.
The heart of the 8051 is the circuitry that generates the clock pulses by which all internal
operations are synchronized.
Pins XTALI and XTAL2 are provided for connecting a resonant network to form an
oscillator.
The 8051 requires an external oscillator circuit. The oscillator circuit usually runs
around 12MHz. the crystal generates 12M pulses in one second. The pulse is used to
synchronize the system operation in a controlled pace.
A machine cycle is minimum amount time a simplest machine instruction must take.
An 8051 machine cycle consists of 12 crystal pulses (ticks).
Instruction with a memory operand needs multiple memory accesses (machine cycles).
E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 8
M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R
7 6 5 4 3 2 1 0
CY AC F0 RS1 RS0 OV - P
• Not all of the addresses from 80h to FFh are used for SFRs, and attempting to use an
address that is not defined, or "empty" results in unpredictable results.
• SFRs are named in certain opcodes by their functional names, such as A or TH0, and are
referenced by other opcodes by their addresses, such as 0E0h or 8Ch.
• Note that any address used in the program must start with a number; thus address E0h for
the A SFR begins with 0.
• Failure to use this number convention will result in an assembler error when the program
is assembled.
Pin Diagram
Pinout Description
Pins 1-8 PORT 1. Each of these pins can be configured as an input or an output.
Pin 9 RESET. A logic one on this pin disables the microcontroller and clears the contents of most
registers. In other words, the positive voltage on this pin resets the microcontroller. By applying
logic zero to this pin, the program starts execution from
the beginning.
Pins10-17 PORT 3. Similar to port 1, each of these pins can serve as general input or output.
Besides, all of them have alternative functions
Pin 10 RXD. Serial asynchronous communication input or Serial synchronous
communication output.
Pin 11 TXD. Serial asynchronous communication output or Serial synchronous
communication clock output.
Pin 12 INT0.External Interrupt 0 input
Pin 13 INT1. External Interrupt 1 input
Pin 14 T0. Counter 0 clock input
Pin 15 T1. Counter 1 clock input
Pin 16 WR. Write to external (additional) RAM
Pin 17 RD. Read from external RAM
Pin 18, 19 XTAL2, XTAL1. Internal oscillator input and output. A quartz crystal which
specifies operating frequency is usually connected to these pins.
Pin 20 GND. Ground.
Pin 21-28 Port 2. If there is no intention to use external memory then these port pins are configured
as general inputs/outputs. In case external memory is used, the higher address byte, i.e.
addresses A8-A15 will appear on this port. Even though memory with capacity of 64Kb is
not used, which means that not all eight port bits are used for its addressing, the rest of
them are not available as
inputs/outputs.
Pin 29 PSEN. If external ROM is used for storing program then a logic zero (0)
appears on it every time the microcontroller reads a byte from memory.
Pin 30 ALE. Prior to reading from external memory, the microcontroller puts the lower address
byte (A0-A7) on P0 and activates the ALE output. After receiving signal from the ALE
pin, the external latch latches the state of P0
and uses it as a memory chip address. Immediately after that, the ALE pin is returned its
previous logic state and P0 is now used as a Data Bus.
Pin 31 EA. By applying logic zero to this pin, P2 and P3 are used for data and address transmission
with no regard to whether there is internal memory or not. It means that even there is a
program written to the microcontroller, it will not be executed. Instead, the program
written to external ROM will be executed. By applying logic one to the EA pin, the
microcontroller will use both
memories, first internal then external (if exists).
Pin 32-39 PORT 0. Similar to P2, if external memory is not used, these pins can be used as general
inputs/outputs. Otherwise, P0 is configured as address output (A0- A7) when the ALE pin
is driven high (1) or as data output (Data Bus) when
the ALE pin is driven low (0).
Pin 40 VCC. +5V power supply.
Internal RAM
Thirty-two bytes from address 00h to 1Fh that make up 32 working registers organized as four
banks of eight registers each. (Bank0- Bank3; with each bank having registers R0-R7)
Each register can be addressed by name (when its bank is selected) or by its RAM address.
Thus R0 of bank 3 is R0 (if bank 3 is currently selected) or address 18h (whether bank 3 is
selected or not).
Bits RS0 and RS1 in the PSW determine which bank of registers is currently in use.
Register banks not selected can be used as general-purpose RAM.
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.
The number of bits that a semiconductor memory chip can store is called chip capacity
o It can be in units of Kbits (kilobits), Mbits (megabits), and so on.
Memory chips are organized into a number of locations within the IC.
o Each location can hold 1 bit, 4 bits, 8 bits, or even 16 bits, depending on how it is
designed internally
The number of locations within a memory IC depends on the address pins
The number of bits that each location can hold is always equal to the
number of data pins
A memory chip contain 2x location, where x is the number of address pins.
Each location contains y bits, where y is the number of data pins on the chip.
The entire chip will contain 2x X y bits
Example 1.1
A given memory chip has 12 address pins and 4 data pins. Find:
(a) The organization, and (b) the capacity.
Solution:
a) This memory chip has 4096 locations (212 = 4096), and each location can hold
4 bits of data. This gives an organization of 4096 × 4, often represented as 4K
× 4.
b) The capacity is equal to 16K bits since there is a total of 4K locations and each
location can hold 4 bits of data.
Example 1.2
A 512K memory chip has 8 pins for data. Find:
(a) The organization, and (b) the number of address pins for this memory chip.
Solution:
a) A memory chip with 8 data pins means that each location within the chip can hold
8 bits of data. To find the number of locations within this memory chip, divide the
capacity by the number of data pins. 512K/8 = 64K; therefore, the organization for
this memory chip is 64K × 8
b) The chip has 16 address lines since 216 = 64K
o In the case of the address buses, while the lower bits of the address from the CPU go
directly to the memory chip address pins, the upper ones are used to activate the CS pin
of the memory chip.
Normally memories are divided into blocks and the output of the decoder selects a given memory
block
o Using simple logic gates
o Using the 74LS138
o Using programmable logics
Logic Gate as
Decoder
74LS138 Decoder
E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 18
M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R
74LS138 as Decoder
Example 1.3 Looking at the design in the above figure, find the address range for the
Following.
(a) Y4, (b) Y2, and (c) Y7.
Solution :
(a) The address range for Y4 is calculated as follows.
A15 A14 A13 A12 A11 A10 A9 A8 A7 A6 A5 A4 A3 A2 A1
A0 01 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1
The above shows that the range for Y4 is 4000H to 4FFFH. In the above figure,
notice that A15 must be 0 for the decoder to be activated. Y4 will be selected
when A14 A13 A12 = 100 (4 in binary). The remaining A11-A0 will be 0 for the lowest
address and 1 for the highest address.
Example 1.4: Design a controller system using 8051.Interface the external RAM of size 16k x 8.
Solution: Given, Memory size: 16k
That means we require 2n=16k :: n address lines
Here n=14 :: A0 to A13 address lines are required.
A14 and A15 are connected through OR gate to CS pin of external RAM.
When A14 and A15 both are low (logic ‘0’), external data memory (RAM) is selected.
Address Decoding (Memory Map) for 16k x 8 RAM.
Example 1.5: Design a controller system using 8051.Interface the external ROM of size 4k x 8.
Solution: Given, Memory size: 4k
That means we require 2n=4k :: n address lines
Here n=12 :: A0 to A11 address lines are required.
Remaining lines A12, A13, A14, A15 & PSEN are connected though OR gate to CS & RD of external
ROM.
When A0 to A0 are low (logic ‘0’), only then external ROM is selected.
Address Decoding (Memory Map) for 4k x 8 RAM.
Module –
2
8051 Instruction Set
General syntax for 8051 assembly language is as follows.
LABEL: OPCODE OPERAND ; COMMENT
OPCODE: Opcode is the symbolic representation of the operation. The assembler converts
the opcode to a unique binary code (machine language).
OPERAND: While opcode specifies what operation to perform, operand specifies where to
perform that action. The operand field generally contains the source and destination of the data.
In some cases only source or destination will be available instead of both. The operand will be
either address of the data, or data itself.
COMMENT: Always comment will begin with ; or // symbol. To improve the program
quality, programmer may always use comments in the program.
Addressing Modes
The CPU can access data in various ways, which are called addressing modes
Immediate
addressing
modes Register Direct
Register
Memory indirect
Indexed
Direct
addressing mode
MOV A,4 ;is same as
MOV A,R4 ;which means copy R4 into A
Register addressing
mode
The SFR (Special Function Register) can be accessed by their names or by their addresses
Example 2-1
Write code to send 55H to ports P1 and P2, using (a) their names (b) their addresses
Solution :
(a) MOV A,#55H ;A=55H
MOV P1,A ;P1=55H
MOV P2,A ;P2=55H
Example 2-2
Show the code to push R5 and A onto the stack and then pop them back them into R2 and B,
where B = A and R2 = R5
Solution:
PUSH 05 ;push R5 onto stack
PUSH 0E0H ;push register A onto stack
POP 0F0H ;pop top of stack into B
;now register B = register A
POP 02 ;pop top of stack into R2
;now R2=R6
Example 2-3
Write a program to copy the value 55H into RAM memory locations 40H to 41H using
(a) direct addressing mode, (b) register indirect addressing mode without a loop, and (c) with a loop
Solution:
(a)
MOV A,#55H ;load A with value 55H
MOV 40H,A ;copy A to RAM location 40H
MOV 41H,A ;copy A to RAM location 41H
(b)
MOV A,#55H ;load A with value 55H
MOV R0,#40H ;load the pointer. R0=40H
MOV @R0,A ;copy A to RAM R0 points to
INC R0 ;increment pointer. Now R0=41h
MOV @R0,A ;copy A to RAM R0 points to
(c)
MOV A,#55H ;A=55H
MOV R0,#40H ;load pointer.R0=40H,
MOV R2,#02 ;load counter, R2=3
AGAIN: MOV @R0,A ;copy 55 to RAM R0 points to
INC R0 ;increment R0 pointer
DJNZ R2,AGAIN ;loop until counter = zero
The advantage is that it makes accessing data dynamic rather than static as in
direct addressing mode
• Looping is not possible in direct addressing mode
Example 2-4
Write a program to clear 16 RAM locations starting at RAM address 60H
Solution:
CLR A ;A=0
MOV R1,#60H ;load pointer, R1=60H
MOV R7,#16 ;load counter, R7=16
AGAIN: MOV @R1,A ;clear RAM R1 points to
INC R1 ;increment R1 pointer
DJNZ R7,AGAIN ;loop until counter=zero
Example 2-5
Write a program to copy a block of 10 bytes of data from 35H to 60H
Solution:
MOV R0,#35H ;source pointer
MOV R1,#60H ;destination pointer
MOV R3,#10 ;counter
BACK: MOV A,@R0 ;get a byte from source
MOV @R1,A ;copy it to destination
INC R0 ;increment source pointer
INC R1 ;increment destination pointer
DJNZ R3,BACK ;keep doing for ten bytes
R0 and R1 are the only registers that can be used for pointers in register
indirect addressing mode
Since R0 and R1 are 8 bits wide, their use is limited to access any information in the
internal RAM
Whether accessing externally connected RAM or on-chip ROM, we need 16-bit pointer
In such case, the DPTR register is used.
Indexed addressing mode is widely used in accessing data elements of look-up table
entries located in the program ROM.
The look-up table allows access to elements of a frequently used table with
minimum operations
The instruction used for this purpose is MOVC A,@A+DPTR
• Use instruction MOVC, “C” means code
• The contents of A are added to the 16-bit register DPTR to form the 16-bit
address of the needed data
Example 2-6
Write a program to get the x value from P1 and send x2 to P2, continuously
Solution:
ORG 0
MOV DPTR,#300H ;LOAD TABLE ADDRESS
MOV A,#0FFH ;A=FF
MOV P1,A ;CONFIGURE P1 INPUT PORT
BACK: MOV A,P1 ;GET X
MOV A,@A+DPTR ;GET X SQAURE FROM TABLE
MOV P2,A ;ISSUE IT TO P2
SJMP BACK ;KEEP DOING IT
ORG 300H
XSQR_TABLE:
DB 0,1,4,9,16,25,36,49,64,81
END
MOV DPTR, #nn Copy the immediate 16-bit number nn to the DPTR register.
A data MOV does not alter the contents of the data source address.
A copy of the data is made from the source and moved to the destination address.
The contents of the destination address are replaced by the source address contents.
Mnemonic Operation
MOV A,#0Flh Move the immediate data byte F1h to the A register
MOV DPTR,#0ABCDh Move the immediate data bytes ABCDh to the DPTR
Mnemonic Operation
MOV Rr, addr Copy data from direct address add to register Rr
MOV instructions that refer to direct addresses above 7Fh that are not SFRs will result
in errors.
The SFRs are physically on the chip; all other addresses above 7Fh do not physically exist.
Moving data to a port changes the port latch; moving data from a port gets data from the port
pins.
Moving data from a direct address to itself is not predictable and could lead to errors.
Mnemonic Operation
MOV 3Ah, #3Ah Copy immediate data byte 3Ah to RAM location 3Ah
MOV R0, 12h Copy data from RAM location 12h to register RO
The indirect addressing mode uses a register to hold the actual address that will finally
be used in the data move;
The register itself is not the address, but rather the number in the register.
Indirect addressing for MOV opcodes uses register R0 or R1, often called "data pointers,"
to hold the address of one of the data locations, which could be a RAM or an SFR
address.
The mnemonic symbol used for indirect addressing is the "at" sign, which is printed as @.
Mnemonic Operation
Mnemonic Operation
MOV @R0, 80h Copy the contents of the port 0 pins to the address in R0
Registers R0. R1, and the DPTR can be used to hold the address of the data byte
in external RAM.
R0 and R1 are limited to external RAM address ranges of 00h to 0FFh, while the
DPTR register can address the RAM space of 0000h to 0FFFFh.
An X is added to the MOV mnemonics to serve as a reminder that the data move is external
to the 8051
Mnemonic Operation
Mnemonic Operation
Data moves between RAM locations and 8051 registers are made by using MOV and
MOVX opcodes. The data is usually of a temporary or "scratch pad" nature and
disappears when the system is powered down.
There are times when access to a preprogrammed mass of data is needed, such as
when using tables of predefined bytes. This data must be permanent to be of repeated
use and is stored in the program ROM.
Access to this data is made possible by using indirect addressing and the A register
in conjunction with either the PC or the DPTR.
In both cases, the number in register A is added to the pointing register to form the address
in ROM where the desired data is to be found.
The data is then fetched from the ROM address so formed and placed in the A register.
The original data in A is lost, and the addressed data takes its place.
Mnemonic Operation
Copy the code byte, found at the ROM address formed by adding
MOVC A, @A+DPTR A and the DPTR, to A
Copy the code byte, found at the ROM address formed by adding
MOVC A, @A+PC A and the PC, to A
Mnemonic Operation
MOV DPTR, #1234h Copy the immediate number 1234h to the DPTR
MOV A, #56h Copy the immediate number 56h to A
The PC is incremented by one (to point to the next instruction) before it is added to A to
form the final address of the code byte.
All data is moved from the code memory to the A register.
MOVC is normally used with internal or external ROM and can address 4K of internal or
64K bytes of external code.
The PUSH and POP opcodes specify the direct address of the data.
The data moves between an area of internal RAM, known as the stack, and the specified
direct address.
The stack pointer special-function register (SP) contains the address in RAM where data from
the source address will be PUSHed, or where data to be POPed to the destination address is
found.
The SP register actually is used in the indirect addressing made but is not named in the mnemonic.
It is implied that the SP holds the indirect address whenever PUSHing or POPing.
A PUSH opcode copies data from the source address to the stack.
SP is incremented by one before the data is copied to the internal RAM location contained in SP
so that the data is stored from low addresses to high addresses in the internal RAM.
The stack grows up in memory as it is PUSHed. Excessive PUSHing can make the stack
exceed 7Fh (the top of internal RAM), after which point data is lost.
A POP opcode copies data from the stack to the destination address.
SP is decremented by one after data is copied from the stack RAM address to the direct
destination to ensure that data placed on the stack is retrieved in the same order as it was
stored.
MOV, PUSH, and POP opcodes all involve copying the data found in the source address to
the destination address; the original data in the source is not changed.
Exchange instructions actually move data in two directions: from source to destination
and from destination to source.
All addressing modes except immediate may be used in the XCH (exchange) opcodes
Arithmetic instructions
The 8051 can perform addition, subtraction. Multiplication and division operations on 8 bit numbers.
The 24 arithmetic opcodes are grouped into as follows
Mnemonic Operation
ADD/ ADDC destination ,source Add source to destination without/with carry (C) flag
ADD A, addr Add A and the address contents; put the sum in A
ADD A, @Rp Add A and the contents of the address in Rp; put the sum in A
Example 2-8
Assume that RAM locations 40 – 44H have the following values.
Write a program to find the sum of the values. At the end of the program, register A
should contain the low byte and R7 the high byte.
40 = (7D) | 41 = (EB) | 42 = (C5) | 43 = (5B) | 44 = (30)
Solution:
MOV R0,#40H ;load pointer
MOV R2,#5 ;load counter
CLR A ;A=0
MOV R7,A ;clear R7
AGAIN: ADD A,@R0 ;add the byte ptr to by R0
JNC NEXT ;if CY=0 don’t add carry
INC R7 ;keep track of carry
NEXT: INC R0 ;increment pointer
DJNZ R2,AGAIN ;repeat until R2 is zero
Example 2-9
Write a program to add two 16-bit numbers. Place the sum in R7 and
R6; R6 should have the lower byte.
Solution:
CLR C ;make CY=0
MOV A, #0E7H ;load the low byte now A=E7H
ADD A, #8DH ;add the low byte
MOV R6, A ;save the low byte sum in R6
MOV A, #3CH ;load the high byte
ADDC A, #3BH ;add with the carry
MOV R7, A ;save the high byte sum
The binary representation of the digits 0 to 9 is called BCD (Binary Coded Decimal)
Unpacked BCD
In unpacked BCD, the lower 4 bits of the number represent the BCD number, and the
rest of the bits are 0
• Ex. 00001001 and 00000101 are unpacked BCD for 9 and 5
Packed BCD
In packed BCD, a single byte has two BCD number in it, one in the lower 4 bits, and
one in the upper 4 bits
• Ex. 0101 1001 is packed BCD for 59H
MOV A, #17H
ADD A, #28H
The result above should have been 17 + 28 = 45 (0100 0101).
To correct this problem, the programmer must add 6 (0110) to the
low digit: 3F + 06 = 45H.
DA Instruction
DA A ;decimal adjust for addition
The DA instruction is provided to correct the aforementioned problem associated with
BCD addition
The DA instruction will add 6 to the lower nibble or higher nibble if need
Example:
MOV ;A=47H first BCD operand
A,#47H ;B=25H second BCD operand
MOV ;hex(binary) addition(A=6CH)
B,#25H ;adjust for BCD addition(A=72H)
The “DA” instruction works only on A.
In other word, while the source can be an operand of any addressing mode, the
destination must be in register A in order for DA to work.
Summary of DA instruction
After an ADD or ADDC instruction
If the lower nibble (4 bits) is greater than 9, or if AC=1, add 0110 to the lower 4 bits
If the upper nibble is greater than 9, or if CY=1, add 0110 to the upper 4 bits
Example 2-10
Assume that 5 BCD data items are stored in RAM locations starting at 40H, as shown
below. Write a program to find the sum of all the numbers. The result must be in BCD.
40=(71) | 41=(11) | 42=(65) | 43=(59) | 44=(37)
Solution:
MOV R0,#40H ;Load pointer
MOV R2,#5 ;Load counter
CLR A ;A=0
MOV R7,A ;Clear R7
AGAIN: ADD A,@R0 ;add the byte pointer to by R0
DA A ;adjust for BCD
JNC NEXT ;if CY=0 don’t accumulate carry
INC R7 ;keep track of carries
NEXT: INC R0 ;increment pointer
DJNZ R2,AGAIN ;repeat until R2 is 0
SUBB when CY = 0
Take the 2’s complement of the subtrahend (source operand)
Add it to the minuend (A)
Invert the carry
CLR C
MOV A,#4CH ;load A with value 4CH
SUBB A,#6EH ;subtract 6E from A
JNC NEXT ;if CY=0 jump to NEXT
CPL A ;if CY=1, take 1’s complement
INC A ;and increment to get 2’s comp
NEXT: MOV R1,A ;save A in R1
Solution:
4C 0100 1100 0100 1100
- 6E 0110 1110 1001 0010
-22 01101 1110
SUBB when CY = 1
This instruction is used for multi-byte numbers and will take care of the borrow of the lower operand
Example 2-11
Write a program to get hex data in the range of 00 – FFH from port 1 and convert it
to decimal. Save it in R7, R6 and R5.
Solution:
MOV A, #0FFH
MOV P1, A ;make P1 an input port
MOV A, P1 ;read data from P1
MOV B, #10 ;B=0A hex
DIV AB ;divide by 10
MOV R7, B ;save lower digit
MOV B, #10
DIV AB ;divide by 10 once more
MOV R6, B ;save the next digit
MOV R5, A ;save the last digit
Logical instructions
A large part of machine control concerns sensing the on-off states of external
switches, making decisions based on the switch states, and then turning external
circuits on or off.
Sensing and control implies a need for byte and bit opcodes that operate on data
using Boolean operators.
All 8051 RAM areas, both data and SFRs, may be manipulated using byte opcodes.
Many of the SFRs, and a unique internal RAM area that is bit addressable, may be
operated upon at the individual bit level.
Bit operators are notably efficient when speed of response is needed.
Bit operators yield compact program code that enhances program execution speed.
The XRL instruction can be used to clear the contents of a register by XORing it with
itself.
Show how XRL A, A clears A, assuming that AH = 45H.
45H 0100 0101
45H 0100 0101
00H 0000 0000
Example 2:12
Read and test P1 to see whether it has the value 45H. If it does, send 99H to P2;
otherwise, it stays cleared.
Solution: XRL can be used to
MOV P2,#00 ;clear P2 see if two registers
MOV P1,#0FFH ;make P1 an input port have the same value
MOV R3,#45H ;R3=45H
MOV A,P1 ;read
P1 XRL A,R3
JNZ EXIT ;jump if A is not If both registers have
0 MOV P2,#99H the same value, 00 is
EXIT: ... placed in A. JNZ and
JZ test the contents of
the accumulator.
MOV A, #56H
CPL A ;now A=A9H
;0101 0110(56H)
;becomes 1010 1001(A9H)
To get the 2’s complement, all we have to do is to add 1 to the 1’s complement
Example 2 – 13
Write a program to read the temperature and test it for the value 75.
According 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:
MOV P1,#0FFH ;make P1 an input port
MOV A,P1 ;read P1 port
CJNE A,#75,OVER;jump if A is not 75
SJMP EXIT ;A=75, exit
OVER: JNC NEXT ;if CY=0 then A>75
MOV R1,A ;CY=1, A<75, save in R1
SJMP EXIT ; and exit
NEXT: MOV R2,A ;A>75, save it in R2
EXIT: ...
RR A ; rotate right
A In rotate right
The 8 bits of the accumulator are rotated right one bit, and
Bit D0 exits from the LSB and enters into MSB, D7
CLR C ;make CY = 0
MOV A,#26H;A = 0010 0110
RRC A ;A = 0001 0011 CY = 0
RRC A ;A = 0000 1001 CY = 1
RRC A ;A = 1000 0100 CY = 1
Example 2- 14
Write a program that finds the number of 1s in a given
byte. MOV R1,#0
MOV R7,#8 ;count=08
MOV A,#97H
AGAIN: RLC A
JNC NEXT ;check for CY
INC R1 ;if CY=1 add to count
NEXT: DJNZ R7,AGAIN
SWAP A
It swaps the lower nibble and the higher nibble
In other words, the lower 4 bits are put into the higher 4 bits and the higher 4 bits are put
into the lower 4 bits
SWAP works only on the accumulator (A)
Example 2- 15
(a) Find the contents of register A in the following code.
(b) In the absence of a SWAP instruction, how would you exchange the nibbles?
Write a simple program to show the process.
Solution:
(a)
MOV A,#72H ;A = 72H
SWAP A ;A = 27H
(b)
MOV A,#72H ;A = 0111 0010
RL A ;A = 1110 0100
RL A ;A = 1100 1001
RL A ;A = 1001 0011
RL A ;A = 0010 0111
Branch instructions
Repeating a sequence of instructions a certain number of times is called a loop.
Loop action is performed by DJNZ reg, Label
• The register is decremented by one
• If it is not zero, it jumps to the target address referred to by the label
• Prior to the start of loop the register is loaded with the counter for the number of
repetitions
• Counter can be R0 – R7 or RAM location
Example 2 – 17
Write a program to
(a) load the accumulator with the value 55H, and
(b) complement the ACC 700 times
MOV A,#55H ;A=55H
MOV R3,#10 ;R3=10, outer loop count
NEXT: MOV R2,#70 ;R2=70, inner loop count
AGAIN: CPL A ;complement A register
DJNZ R2,AGAIN ;repeat it 70 times
DJNZ R3,NEXT
Conditional Jumps
JZ label ; jump if
A=0
Jump only if a certain condition is met.
MOV A,R0 ;A=R0 Can be used only for
JZ OVER ;jump if A = 0 register A,
MOV A,R1 ;A=R1 not any other register
JZ OVER ;jump if A = 0
...
OVER:
Example 2 – 18
Find the sum of the values 79H, F5H, E2H. Put the sum in registers R0 (low byte) and
R5 (high byte).
MOV A,#0 ;A=0
MOV R5,A ;clear R5
ADD A,#79H ;A=0+79H=79H
JNC N_1 ;if CY=0, add next number
INC R5 ;if CY=1, increment R5
N_1: ADD A,#0F5H ;A=79+F5=6E and CY=1
JNC N_2 ;jump if CY=0
INC R5 ;if CY=1,increment R5 (R5=1)
N_2: ADD A,#0E2H ;A=6E+E2=50 and CY=1
JNC OVER ;jump if CY=0
INC R5 ;if CY=1, increment 5
OVER: MOV R0,A ;now R0=50H, and R5=02
Example 2 – 19
Program using JNB and JBC
instructions.
LOOP: MOV A,#10h ; A = 10h
MOV R0,A ;RO = 10h
ADDA: ADD A,R0 ;add RO to A
JNC ADDA ;if the carry flag is 0, then ‘no
;carry’(NC) is true
;jump to address ADDA
;jump until A is F0h
;C flag is set on the next ADD & ‘no
;carry’(NC) is false
; do the next instruction
Unconditional Jumps
The unconditional jump is a jump in which control is transferred unconditionally to the
target location.
Unconditional jumps do not test any bit or byte to determine whether the jump should be taken.
The jump is always taken.
JBC bit, target Jump to target if bit = 1, clear bit (jump if bit, then clear)
1. Write a program to add the values of locations 50H and 51H and store the result in
locations in 52h and 53H.
2. Write a program to store data FFH into RAM memory locations 50H to 58H using
direct addressing mode
3. Write a program to subtract a 16 bit number stored at locations 51H-52H from 55H-
56H and store the result in locations 40H and 41H. Assume that the least significant byte
of data or the result is stored in low address. If the result is positive, then store 00H, else
store 01H in 42H.
4. Write a program to add two 16 bit numbers stored at locations 51H-52H and 55H-56H
and store the result in locations 40H, 41H and 42H. Assume that the least significant
byte of data and the result is stored in low address and the most significant byte of data
or the result is stored in high address.
5. Write a program to store data FFH into RAM memory locations 50H to 58H using
indirect addressing mode.
6. Write a program to add two Binary Coded Decimal (BCD) numbers stored at locations
60H and 61H and store the result in BCD at memory locations 52H and 53H. Assume
that the least significant byte of the result is stored in low address.
8. Write a program to compute 1 + 2 + 3 + N (say N=15) and save the sum at70H
9. Write a program to multiply two 8 bit numbers stored at locations 70H and 71H and
store the result at memory locations 52H and 53H. Assume that the least significant byte
of the result is stored in low address.
10. Write a program to find the average of five 8 bit numbers. Store the result in 55H.
(Assume that after adding five 8 bit numbers, the result is 8 bit only).
ORG 0000H
MOV 40H,#05H
MOV 41H,#55H
MOV 42H,#06H
MOV 43H,#1AH
MOV 44H,#09H
MOV R0,#40H
MOV R5,#05H
MOV B,R5
CLR A
Loop: ADD A,@R0
INC R0
DJNZ
R5,Loop DIV
A B
MOV 55H,A
END
11. Write a program to find the cube of an 8 bit number program is as follows
ORG 0000H
MOV R1,#N
MOV A,R1
MOV B,R1
MUL A B
MOV R2, B
MOV B, R1
MUL A B
MOV 50,A
MOV 51,B
MOV A,R2
MOV B, R1
MUL AB
ADD A, 51H
MOV 51H, A
MOV 52H, B
MOV A, #00H
ADDC A, 52H
MOV 52H, A
END
12. Write a program to exchange the lower nibble of data present in external memory
6000H and 6001H
13. Write a program to count the number of and o's of 8 bit data stored in location 6000H.
15. Two 8 bit numbers are stored in location 1000h and 1001h of external data memory.
Write a program to find the GCD of the numbers and store the result in 2000h.
ALGORITHM
Step 1 :Initialize external data memory with data and DPTR with address
Step 2 :Load A and TEMP with the operands
Step 3 :Are the two operands equal? If yes, go to step 9
Step 4 :Is (A) greater than (TEMP) ? If yes, go to step 6
Step 5 :Exchange (A) with (TEMP) such that A contains the bigger number
Step 6 :Perform division operation (contents of A with contents of TEMP)
Step 7 :If the remainder is zero, go to step 9
Step 8 :Move the remainder into A and go to step 4
Step 9 :Save the contents 'of TEMP in memory and terminate the program
****************************************************************************************
Module – 3
Example 3-1
Show the stack and stack pointer from the following. Assume the default stack area.
MOV R6, #25H
MOV R1, #12H
MOV R4, #0F3H
PUSH 6
PUSH 1
PUSH 4
Solution:
Example 3-2
Examining the stack, show the contents of the register and SP after execution of the
following instructions. All value are in hex.
POP 3 ; POP stack into R3
POP 5 ; POP stack into R5
POP 2 ; POP stack into R2
Solution:
The CPU also uses the stack to save the address of the instruction just below the CALL
instruction
o This is how the CPU knows where to resume when it returns from the called
subroutine.
The reason of incrementing SP after push is
o Make sure that the stack is growing toward RAM location 7FH, from lower to upper
addresses.
If the stack pointer were decremented after push
o We would be using RAM locations 7, 6, 5, etc. which belong to R7 to R0 of bank 0,
the default register bank.
When 8051 is powered up, register bank 1 and the stack are using the same memory space
o We can reallocate another section of RAM to the stack.
Example 3-3
Examining the stack, show the contents of the register and SP after execution of the
following instructions. All value are in hex.
MOV SP, #5FH ;make RAM location 60H, first stack location
MOV R2, #25H
MOV R1, #12H
MOV R4, #0F3H
PUSH 2
PUSH 1
PUSH 4
Solution:
RETI
Pops two bytes from the stack into the program counter (PC) and reset the interrupt enable Flip-
Flops.
The only difference between the RET and RETI instructions is the enabling of the interrupt logic
when RETI is used.
RET is used at the ends of subroutines called by an opcode. RETI is used by subroutines
called by an interrupt
The four 8-bit I/O ports P0, P1, P2 and P3 each uses 8 pins
All the ports upon RESET are configured as input, ready to be used as input ports
o When the first 0 is written to a port, it becomes an output
o To reconfigure it as an input, a 1 must be sent to the port
o To use any of these ports as an input port, it must be programmed
Port 0
Port 0 can be used for input or output, each pin must
be connected externally to a 10K ohm pull-up resistor
o 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
Example 3-5
The following code will continuously send out to port 0 the alternating value 55H and
AAH
BACK: MOV A,#55H
MOV P0,A
ACALL DELAY
MOV A,#0AAH
MOV P0,A
ACALL DELAY
SJMP BACK
In order to make port 0 an input, the port must be programmed by writing 1 to all the bits
Example 3-6
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
MOV A,#0FFH ;A=FF hex
MOV P0,A ;make P0 an i/p port by writing it all 1s
BACK:MOV A,P0 ;get data from P0
MOV P1,A ;send it to port 1
SJMP BACK ;keep doing it
Port 1
Port 1 can be used as input or output
o In contrast to port 0, this port does not need any pull-up resistors since it already has pull-
up resistors internally
o Upon reset, port 1 is configured as an input port
o To make port 1 an input port, it must be programmed as such by writing 1 to all its bits
Example 3-7
The following code will continuously send out to port 1 the alternating value 55H and
AAH
MOV A,#55H
BACK: MOV P1,A
ACALL DELAY
CPL A
SJMP BACK
A= 01010101(55h) =>Complementing gives 10101010(AAh)
Example 3-8
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
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 reg R7
ACALL DELAY ;wait
MOV A,P1 ;another data from P1
MOV R5,A ;save it to in reg R5
Example 3-9
Write a program to toggle all the bits of port1 by sending to it the values 55h and AAh
continuously. Put a time delay in between each issuing of data to port1.
ORG 0
BACK: MOV A,#55H ; Load A with 55h
MOV P1,A ; Send 55h to port1
ACALL DELAY ; Call the subroutine DELAY
MOV A,#0AAH ; Load A with AAh
MOV P1,A ; Send AAh to port1
ACALL DELAY ; Call the subroutine DELAY
SJMP BACK ; Keep doing this indefinitely
Delay Subroutine
ORG 300H
DELAY: MOV R5, #0FFH ; R5 works as counter with 256 counts
AGAIN: DJNZ R5, AGAIN ; Stay here until R5 becomes 0
RET ; Return to Called program
END
Example 3-10
Rewrite the previous program efficiently.
ORG 0
MOV A,#55H ; Load A with 55h
BACK: MOV P1,A ; Send 55h to port1
ACALL DELAY ; Call the subroutine DELAY
CPL A ; Complements A, so that A becomes
SJMP BACK ;AAh
Keep doing this indefinitely
------ Delay Subroutine---------
ORG 300H
DELAY: MOV R5, #0FFH ; R5 works as counter with 256 counts
AGAIN: DJNZ R5, AGAIN ; Stay here until R5 becomes 0
RET ; Return to Called program
END
Example 3-11
Write a program to toggle the bits of port1 delay which depends on the value of a
number in R0.
ORG 0
BACK: MOV A,#0H
MOV P1,A ; Send 0h to port P1
MOV R0, #30H ; Required count value for generating
delay
ACALL DELAY; Call the subroutine
CPL A DELAY
MOV P1,A ; Complement
Send AAh toA to toggle
MOV R0, #0FFH port1 ; required count value for generating
ACALLdelay
DELAY ; Call the subroutine DELAY
SJMP BACK ; Keep doing this indefinitely
------ Delay Subroutine---------
ORG 300H
DELAY: NOP ; Do nothing
AGAIN: DJNZ R0, AGAIN ; Stay here until R0 becomes 0
RET ; Return to the Called
program
Example 3-12
Write a program to perform the following:
(a) Keep monitoring the P1.2 bit until it becomes high
(b) When P1.2 becomes high, write value 45H to port 0
(c) Send a high-to-low (H-to-L) pulse to P2.3
SETB P1.2 ;make P1.2 an input
MOV A,#45H ;A=45H
AGAIN: JNB P1.2,AGAIN ;get out when P1.2=1
MOV P0,A ;issue A to P0
SETB P2.3 ;make P2.3 high
CLR P2.3 ;make P2.3 low for H-to-
L
Example 3-13
Assume that bit P2.3 is an input and represents the condition of an
oven. If it goes high, it means that the oven is hot. Monitor the bit
continuously.
Whenever it goes high, send a high-to-low pulse to port P1.5 to turn on a
HERE: JNB P2.3,HERE ;keep monitoring for high
SETB P1.5 ;set bit P1.5=1
CLR P1.5 ;make high-to-low
SJMP HERE ;keep repeating
Example 3-14
A switch is connected to pin P1.7. Write a program to check the status of SW and
perform the following:
(a) If SW=0, send letter ‘N’ to P2
(b) If SW=1, send letter ‘Y’ to P2
Module – 4
8051 Timers and Serial Port
Timers/Counters are used generally for
Time reference
Creating delay
Wave form properties measurement
Periodic interrupt generation
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
Timer in 8051 is used as timer, counter and baud rate generator. Timer always counts up irrespective of
whether it is used as timer, counter, or baud rate generator: Timer is always incremented by the
microcontroller. The time taken to count one digit up is based on master clock frequency.
TMOD Register
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.
TIMER MODES
Timers can operate in four different modes. They are as follows
Timer Mode-0: In this mode, the timer is used as a 13-bit UP counter as follows.
The lower 5 bits of TLX and 8 bits of THX are used for the 13-bit count. Upper 3 bits of TLX
are ignored. When the counter rolls over from all 0's to all 1's, TFX flag is set and an
interrupt is generated. The input pulse is obtained from the previous stage. If TR1/0 bit is 1
and Gate bit is 0, the counter continues counting up. If TR1/0 bit is 1 and Gate bit is 1, then
the operation of the counter is controlled by input. This mode is useful to measure the width of a
given pulse fed to input.
Timer Mode-1: This mode is similar to mode-0 except for the fact that the Timer operates in 16-
bit mode.
Mode 1:
Load the TMOD value register indicating which timer (0 or 1) is to be used and which timer
mode is selected.
Load registers TL and TH with initial count values.
Start the timer by the instruction “SETB TR0” for timer 0 and “SETB TR1” for timer 1.
Keep monitoring the timer flag (TF) with the “JNB TFx, target” instruction to see if it
is raised. Get out of the loop when TF becomes high.
Stop the timer with the instructions “CLR TR0” or “CLR TR1”, for timer 0 and timer
1, respectively.
Clear the TF flag for the next round with the instruction “CLR TF0” or “CLR TF1”, for
timer 0 and timer 1, respectively.
Go back to step 2 to load TH and TL again.
Mode 0:
The programming techniques mentioned here are also applicable to counter/timer mode 0. The only
difference is in the number of bits of the initialization value.
Mode 2:
Load the TMOD value register indicating which timer (0 or 1) is to be used; select
timer mode 2.
Load TH register with the initial count value. As it is an 8-bit timer, the valid range is
from 00 to FFH.
Start the timer.
Keep monitoring the timer flag (TFx) with the “JNB TFx, target” instruction to see if it
is raised. Get out of the loop when TFx goes high.
Clear the TFx flag.
Go back to step 4, since mode 2 is auto-reload.
Example 4-1
Indicate which mode and which timer are 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 4-2
Find the timer’s clock frequency and its period for various 8051-based system, with the crystal
frequency 11.0592 MHz when C/T bit of TMOD is 0.
Example 4-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. Analyze the program
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-4
In Example 9-4, calculate the amount of time delay in the DELAY subroutine generated by the timer.
Assume XTAL = 11.0592 MHz.
Solution:
The timer works with a clock frequency of 1/12 of the XTAL frequency; therefore, we have
11.0592 MHz / 12 = 921.6 kHz as the timer frequency. As a result, each clock has a
period of T
=1/921.6kHz = 1.085us. In other words, Timer 0 counts up each 1.085 us resulting in delay
= number of counts × 1.085us.
The number of counts for the roll over is FFFFH – FFF2H = 0DH (13decimal). However, we
add one to 13 because of the extra clock needed when it rolls over from FFFF to 0 and raise the
TF flag. This gives 14× 1.085us = 15.19us for half the pulse. For the entire period it is T = 2×
15.19us = 30.38us as the time delay generated by the timer.
Example 4-5
The following program generates a square wave on P1.5 continuously using timer 1 for a time delay.
Find the frequency of the square wave if XTAL = 11.0592 MHz. In your calculation do not
include the overhead due to Instructions in the loop.
MOV TMOD,#10 ;Timer 1, mod 1 (16-bitmode)
AGAIN: MOV TL1,#34H ;TL1=34H, low byte of timer
MOV TH1,#76H ;TH1=76H, high byte timer
SETB TR1 ;start the timer 1
BACK: JNB TF1,BACK ;till timer rolls
over
CLR TR1 ;stop the timer 1
CPL P1.5 ;comp. p1. to get hi, lo
CLR TF1 ;clear timer flag 1
SJMP AGAIN ;is not auto-reload
Solution:
Since FFFFH – 7634H = 89CBH + 1 = 89CCH and 89CCH = 35276 clock count and 35276
× 1.085 us = 38.274 ms for half of the square wave. The frequency = 13.064Hz. Also notice that
the high portion and low portion of the square wave pulse are equal. In the above
calculation, the overhead due to all the instruction in the loop is not included.
Example 4-6
Write a program to continuously generate a square wave of 2 kHz frequency on pin P1.5 using timer
1. Assume the crystal oscillator frequency to be 12 MHz.
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.
Example4-6
Write a program segment that uses timer 1 in mode 2 to toggle P1.0 once whenever the counter
reaches a count of 100. Assume the timer clock is taken from external source P3.5 (T1).
The TMOD value is 60H The initialization value to be loaded into TH1 is 256 - 100 = 156 = 9CH
SERIAL COMMUNICATION
The 8051 microcontroller is parallel device that transfers eight bits of data simultaneously over eight
data lines to parallel I/O devices. Parallel data transfer over a long is very expensive. Hence, a
serial communication is widely used in long distance communication. In serial data
communication, 8-bit data is converted to serial bits using a parallel in serial out shift register and
then it is transmitted over a single data line. The data byte is always transmitted with least significant
bit first.
Communication Links
1. Simplex communication link: In simplex transmission, the line is dedicated for transmission.
The transmitter sends and the receiver receives the data.
2. Half duplex communication link: In half duplex, the communication link can be used for
either transmission or reception. Data is transmitted in only one direction at a time.
3. Full duplex communication link: If the data is transmitted in both ways at the same time,
it is a full duplex i.e. transmission and reception can proceed simultaneously. This
communication link requires two wires for data, one for transmission and one for reception.
2. Asynchronous Serial data transmission: In this, different clock sources are used for
transmitter and receiver. In this mode, data is transmitted with start and stop bits. A
transmission begins with start bit, followed by data and then stop bit. For error
checking purpose parity bit is included just prior to stop bit. In Asynchronous serial
data communication a single byte is transmitted at a time.
Baud rate: The rate at which the data is transmitted is called baud or transfer rate. The baud rate
is the reciprocal of the time to send one bit. In asynchronous transmission, baud rate is not
equal to number of bits per second. This is because; each byte is preceded by a start bit and followed
by parity and stop bit. For example, in synchronous transmission, if data is transmitted with
9600 baud, it means that 9600 bits are transmitted in one second. For bit transmission time = 1
second/ 9600 =
0.104 ms.
2. SCON register: The contents of the Serial Control (SCON) register are shown below.
This register contains mode selection bits, serial port interrupt bit (TI and RI) and also the ninth
data bit for transmission and reception (TB8 and RB8).
SM0, SM1:They determine the framing of data by specifying the number of bits per character, and
the start and stop bits
3. PCON register: The SMOD bit (bit 7) of PCON register controls the baud rate in
asynchronous mode transmission
referred as MARK while logic zero (0) is represented by +3 to +25V and referred as SPACE.
For this reason to connect any RS232 to a microcontroller system we must use voltage converters
such as MAX232 to convert the TTL logic level to RS232 voltage levels and vice-versa.
MAX232 IC chips are commonly referred as line drivers. In RS232 standard we use two types
of connectors. DB9 connector or DB25 connector.
Example 4.7
With XTAL = 11.0592 MHz, find the TH1 value needed to have thefollowing 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 toset baud rate.
(a) 28,800 / 3 = 9600 where -3 = FD (hex) is loaded into TH1
(b)28,800 / 12 = 2400 where -12 = F4 (hex) is loaded into TH1
(c)28,800 / 24 = 1200 where -24 = E8 (hex) is loaded into TH1
Example 4.8
Write a program for the 8051 to transfer letter ‘A’ serially at 4800- baud rate, 8 bit data, 1 stop bit
continuously.
Solution:
MOV TMOD, #20H ;timer 1,mode 2(auto reload)
MOV TH1, #-6 ;4800 baud rate
MOV SCON, #50H ;8-bit, 1 stop, REN enabled
SETB TR1 ;start timer 1
AGAIN: MOV SBUF, #”A” ;letter “A”to transfer
HERE: JNB TI, HERE ;wait for the last bit
CLR TI ;clear TI for next char
SJMP AGAIN ;keep sending A
Example 4.9
Write a program for the 8051 to transfer “YES” serially at 9600 baud, 8-bit data, 1 stop bit, do this
continuously
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 A, #”Y” ;transfer “Y”
ACALL TRANS
MOV A, #”E” ;transfer “E”
ACALL TRANS
MOV A, #”S” ;transfer “S”
ACALL TRANS
SJMP AGAIN ;keep doing it serial data transfer subroutine
TRANS: MOV SBUF,A ;load SBUF
HERE: JNB TI,HERE ;wait for the last bit
CLR TI ;get ready for next byte
RET
Example 4.10
Write a C program for 8051 to transfer the letter “A” serially at 4800 baud continuously. Use 8-bit data and 1
stop bit.
Solution:
#include
<reg51.h> void
main(void)
{
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFA; //4800 baud
rate SCON=0x50;
TR1=1;
while (1) {
SBUF=‘A’; //place value in buffer
while (TI==0);
TI=0;
}
}
Example 4.11
Write an 8051 C program to transfer the message “YES” serially at 9600 baud, 8-bit data, 1 stop bit.
Do this continuously.
Solution:
#include <reg51.h>
void SerTx(unsigned char);
void main(void)
{
TMOD=0x20; //use Timer 1, mode
2 TH1=0xFD; //9600 baud rate
SCON=0x50;
TR1=1; //start
timer While (1) {
SerTx(‘Y’);
SerTx(‘E’);
SerTx(‘S’);
}
}
void SerTx(unsigned char x)
{
SBUF=x; //place value in
buffer While (TI==0); //wait until
transmitted TI=0;
}
Module – 5
8051 Interrupts and Interfacing Applications
Interrupt is one of the most important and powerful concepts and features in
microcontroller/processor applications. Almost all the real world and real time systems built around
microcontrollers and microprocessors make use of interrupts.
What is an Interrupt?
An interrupt refer to a notification, communicated to the controller, by a hardware device or software, on
receipt of which controller momentarily stops and responds to the interrupt. Whenever an interrupt
occurs the controller completes the execution of the current instruction and starts the execution of an
Interrupt Service Routine (ISR) or Interrupt Handler.
ISR is a piece of code that tells the processor or controller what to do when the interrupt occurs. After the
execution of ISR, controller returns back to the instruction it has jumped from (before the interrupt was
received). The interrupts can be either hardware interrupts or software interrupts.
Need of interrupts
An application built around microcontrollers generally has the following structure. It takes input from
devices like keypad, ADC etc; processes the input using certain algorithm; and generates an output
which is either displayed using devices like seven segment, LCD or used further to operate other devices
like motors etc. In such designs, controllers interact with the inbuilt devices like timers and other
interfaced peripherals like sensors, serial port etc. The programmer needs to monitor their status
regularly like whether the sensor is giving output, whether a signal has been received or transmitted,
whether timer has finished counting, or if an interfaced device needs service from the controller, and
so on. This state of continuous monitoring is known as polling.
In polling, the microcontroller keeps checking the status of other devices; and while doing so it does
no other operation and consumes all its processing time for monitoring. This problem can be addressed
by using interrupts. In interrupt method, the controller responds to only when an interruption occurs.
Thus in interrupt method, controller is not required to regularly monitor the status (flags, signals etc.) of
interfaced and inbuilt devices.
To understand the difference better, consider the following. The polling method is very much similar to
a salesperson. The salesman goes door-to-door requesting to buy its product or service. Like
controller keeps monitoring the flags or signals one by one for all devices and caters to whichever needs
its service. Interrupt, on the other hand, is very similar to a shopkeeper. Whosoever needs a service or
product goes to him and apprises him of his/her needs. In our case, when the flags or signals are
received, they notify the controller that they need its service.
Multiple interrupts
What would happen if multiple interrupts are received by a microcontroller at the same instant? In such
a case, the controller assigns priorities to the interrupts. Thus the interrupt with the highest priority
is served first. However the priority of interrupts can be changed configuring the appropriate registers
in the code.
8051 Interrupts
The 8051 controller has six hardware interrupts of which five are available to the programmer. These
are as follows:
1. RESET interrupt – This is also known as Power on Reset (POR). When the RESET interrupt
is received, the controller restarts executing code from 0000H location. This is an interrupt which is not
available to or, better to say, need not be available to the programmer.
2. Timer interrupts – Each Timer is associated with a Timer interrupt. A timer interrupt notifies
the microcontroller that the corresponding Timer has finished counting.
3. External interrupts – There are two external interrupts EX0 and EX1 to serve external
devices. Both these interrupts are active low. In AT89C51, P3.2 (INT0) and P3.3 (INT1) pins are
available for external interrupts 0 and 1 respectively. An external interrupt notifies the
microcontroller that an external device needs its service.
4. Serial interrupt – This interrupt is used for serial communication. When enabled, it notifies the
controller whether a byte has been received or transmitted.
When an interrupt is received, the controller stops after executing the current instruction. It
transfers the content of program counter into stack. It also stores the current status of the
interrupts internally but not on stack. After this, it jumps to the memory location specified by
Interrupt Vector Table (IVT). After that the code written on that memory area gets executed.
This code is known as the Interrupt Service Routine (ISR) or interrupt handler. ISR is a code
written by the programmer to handle or service the interrupt.
Programming Interrupts
While programming interrupts, first thing to do is to specify the microcontroller which interrupts must
be served. This is done by configuring the Interrupt Enable (IE) register which enables or disables the
various available interrupts. The Interrupt Enable register has following bits to enable/disable the
hardware interrupts of the 8051 controller.
To enable any of the interrupts, first the EA bit must be set to 1. After that the bits corresponding
to the desired interrupts are enabled. ET0, ET1 and ET2 bits are used to enable the Timer
Interrupts 0, 1 and 2, respectively. In AT89C51, there are only two timers, so ET2 is not used.
EX0 and EX1 are used to enable the external interrupts 0 and 1. ES is used for serial interrupt.
EA bit acts as a lock bit. If any of the interrupt bits are enabled but EA bit is not set, the interrupt will
not function. By default all the interrupts are in disabled mode.
Note that the IE register is bit addressable and individual interrupt bits can also be accessed.
Note that the IE register is bit addressable and individual interrupt bits can also be accessed.
For example –
IE = 0x81; enables External Interrupt0
(EX0) IE = 0x88; enables Serial Interrupt
Setting the bits of IE register is necessary and sufficient to enable the interrupts. Next step is to specify
the controller what to do when an interrupt occurs. This is done by writing a subroutine or
function for the interrupt. This is the ISR and gets automatically called when an interrupt occurs.
It is not required to call the Interrupt Subroutine explicitly in the code.
An important thing is that the definition of a subroutine must have the keyword interrupt followed
by the interrupt number. A subroutine for a particular interrupt is identified by this number.
0 External0 EX0
1 Timer0 IT0
2 External1 EX1
3 Timer1 IT1
4 Serial ES
5 Timer2 ET2
3
{
<Body of ISR>
}
For example : Interrupt routine for External Interrupt0 (EX0)
5. Write subroutine for Timer Interrupt. The interrupt number is 1 for Timer0 and 3 for Timer1.
Setting the IT0 and IT1 bits make the external interrupt 0 and 1 edge triggered respectively. By default
these bits are cleared and so external interrupt is level triggered.
Note: For a level trigger interrupt, the INTx pin must remain low until the start of the ISR and
should return to high before the end of ISR. If the low at INTx pin goes high before the start of ISR,
interrupt will not be generated. Also if the INTx pin remains low even after the end of ISR, the
interrupt will be generated once again. This is the reason why level trigger interrupt (low) at INTx
pin must be four machine cycles long and not greater than or smaller than this.
Example 5.2
//Edge trigger external interrupt
void main()
{
IE = 0x84;
IT1 = 1;
while(1);
}
void ISR_ex1(void) interrupt 2
{
<body of interrupt>
}
Example 5.3
Send ‘A’ from serial port with the use of interrupt
// Sending ‘A’ through serial port with interrupt
// XTAL frequency 11.0592MHz
void main()
{
TMOD = 0x20;
TH1 = -1;
SCON = 0x50;
TR1 = 1;
IE = 0x90;
while(1);
}
void ISR_sc(void) interrupt 4
{
if(TI==1)
{
SBUF = ‘A’;
TI = 0;
}
else
RI = 0;
}
Example 5.4
// Receive data from serial port through interrupt
// XTAL frequency 11.0592MHz
void main()
{
TMOD = 0x20;
TH1 = -1;
SCON = 0x50;
TR1 = 1;
IE = 0x90;
while(1);
}
void ISR_sc(void) interrupt 4
{
unsigned char val;
if(TI==1)
{
TI = 0;
}
else
{
val = SBUF;
RI = 0;
}
}
It has a permanent magnet rotor called the shaft which is surrounded by a stator. Commonly used
stepper motors have four stator windings that are paired with a center – tapped common. Such motors
are called as four-phase or unipolar stepper motor. The stator is a magnet over which the electric
coil is wound. One end of the coil are connected commonly either to ground or +5V. The other
end is provided with a fixed sequence such that the motor rotates in a particular direction. Stepper
motor shaft moves in a fixed repeatable increment, which allows one to move it to a precise
position. Direction of the rotation is dictated by the stator poles. Stator poles are determined by the
current sent through the wire coils.
Step angle: Step angle is defined as the minimum degree of rotation with a single step.
No of steps per revolution = 360° / step angle Steps per second = (rpm x steps per revolution) / 60
Example: step angle = 2° No of steps per revolution = 180
Switching Sequence of Motor: As discussed earlier the coils need to be energized for the
rotation. This can be done by sending a bits sequence to one end of the coil while the other end is
commonly connected. The bit sequence sent can make either one phase ON or two phase ON for a
full step sequence or it can be a combination of one and two phase ON for half step sequence.
Both are tabulated below.
The following example 1 to example 6 shown below will elaborate on the discussion done above:
Example 1: Write an ALP to rotate the stepper motor clockwise / anticlockwise continuously with full
step sequence.
Program:
MOV A, #66H
BACK: MOV P1, A
RR A
ACALL DELAY
SJMP BACK
DELAY: MOV R1, #100
UP1: MOV R2, #50
UP: DJNZ R2, UP
DJNZ R1, UP1
RET
The R-2R ladder DAC, which is a binary weighted DAC that uses a repeating cascaded structure
of resistor values R and 2R. This improves the precision due to the relative ease of producing equal
valued matched resistors (or current sources). However, wide converters perform slowly due to
increasingly large RC-constants for each added R-2R link.
The first criterion for judging a DAC is its resolution, which is a function of the number of binary
inputs. The common ones are 8, 10, and 12 bits. The number of data bit inputs decides the
resolution of the DAC since the number of analog output levels is equal to 2n, where n is the
number of data bit inputs. DAC0808: The digital inputs are converter to current Iout, and by
connecting a resistor to the Iout pin, we can convert the result to voltage. The total current Iout is a
function of the binary numbers at the D0-D7 inputs of the DAC0808 and the reference current Iref ,
and is as follows:
Usually reference current is 2mA. Ideally we connect the output pin to a resistor, convert this current
to voltage, and monitor the output on the scope. But this can cause inaccuracy; hence an opamp is
used to convert the output current to voltage. The 8051 connection to DAC0808 is as shown in
E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 92
.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS
The following examples 9, 10 and 11 will show the generation of waveforms using DAC0808.
CLK IN and CLK R: CLK IN is an input pin connected to an external clock source. To use the
internal clock generator (also called self-clocking), CLK IN and CLK R pins are connected to a
capacitor and a resistor and the clock frequency is determined by:
Typical values are R = 10K ohms and C =150pF. We get f = 606 kHz and the conversion time is
110μs.
Vref/2 : It is used for the reference voltage. If this pin is open (not connected), the analog input voltage
is in the range of 0 to 5 volts (the same as the Vcc pin). If the analog input range needs to be 0 to
4 volts, Vref/2 is connected to 2 volts. Step size is the smallest change can be discerned by an
ADC
D0-D7: The digital data output pins. These are tri-state buffered. The converted data is accessed only
when CS =0 and RD is forced low. To calculate the output voltage, use the following formula
Analog ground and digital ground: Analog ground is connected to the ground of the analog Vin
and digital ground is connected to the ground of the Vcc pin. To isolate the analog Vin signal from
transient voltages caused by digital switching of the output D0 – D7. This contributes to the
accuracy of the digital data output.
Vin(+) & Vin(-): Differential analog inputs where Vin = Vin (+) – Vin (-). Vin (-) is connected to
ground and Vin (+) is used as the analog input to be converted.
RD: Is “output enable” a high-to-low RD pulse is used to get the 8-bit converted data out of ADC804.
INTR: It is “end of conversion” When the conversion is finished, it goes low to signal the CPU
that the converted data is ready to be picked up.
WR: It is “start conversion” When WR makes a low-to-high transition, ADC804 starts converting the
analog input value of Vin to an 8- bit digital number.
The following steps must be followed for data conversion by the ADC804 chip:
1. Make CS= 0 and send a L-to-H pulse to pin WR to start conversion.
2. Monitor the INTR pin, if high keep polling but if low, conversion is complete, go to next step.
3. Make CS= 0 and send a H-to-L pulse to pin RD to get the data
out The following figure shows the read and write timing for
ADC804.
The following figures shows the self-clocking with the RC component for frequency and the external
frequency connected to XTAL2 of 8051.
LCD Interfacing:
LCD is finding widespread use replacing LEDs for the following reasons: The declining prices of LCD
The ability to display numbers, characters, and graphics Incorporation of a refreshing controller
into the LCD, thereby relieving the CPU of the task of refreshing the LCD Ease of programming
for characters and graphics.
Command codes
LCD timing diagram for reading and writing is as shown in the below figures.
Sending Data/ Commands to LCDs with Time Delay: To send any of the commands to the LCD,
make pin RS=0. For data, make RS=1. Then send a high-to-low pulse to the E pin to enable the
internal latch of the LCD.
****************************************************************************************