Upload
payal-singh
View
177
Download
8
Tags:
Embed Size (px)
Citation preview
Embedded Embedded Systems with Systems with 8051 8051 µCµC
Part 1Part 1
8051 8051 µCµC
INTRODUCTIONINTRODUCTION
µPs Vs µCsµPs Vs µCs
On the left is a block diagram of a general purpose microprocessor On the left is a block diagram of a general purpose microprocessor based computer like the PCs and the laptops all of us are familiar with based computer like the PCs and the laptops all of us are familiar with [minus the output device (f.e. CRT display), the input device (f.e. [minus the output device (f.e. CRT display), the input device (f.e. keyboard) and the secondary storage (f.e. hard disk)]keyboard) and the secondary storage (f.e. hard disk)]
To the right is the block diagram of the same computer, implemented To the right is the block diagram of the same computer, implemented on a single chip of silicon. on a single chip of silicon.
We call this one chip implementation of a computer, or We call this one chip implementation of a computer, or
computer-on-a-single-chip, a MICROCONTROLLERcomputer-on-a-single-chip, a MICROCONTROLLER
µCsµCs in Embedded Systems in Embedded Systems
The Intel 8051 µCThe Intel 8051 µC In 1981, Intel came out with an 8-bit uC called In 1981, Intel came out with an 8-bit uC called
80518051
This uC had 128 bytes of RAM, 4K (4096) bytes This uC had 128 bytes of RAM, 4K (4096) bytes of on-chip ROM, 2 timers, 1 serial port, and 4 8-of on-chip ROM, 2 timers, 1 serial port, and 4 8-bit wide I/O ports all on a single chipbit wide I/O ports all on a single chip
The 8051 is an 8-bit processor, meaning that the The 8051 is an 8-bit processor, meaning that the CPU can work on only 8 bits of data at a time. CPU can work on only 8 bits of data at a time.
Data larger than 8 bits has to be broken into 8-Data larger than 8 bits has to be broken into 8-bit pieces to be processed by the CPU. bit pieces to be processed by the CPU.
Although the 8051 can have a maximum of 64K Although the 8051 can have a maximum of 64K bytes of on-chip ROM, many manufacturers bytes of on-chip ROM, many manufacturers have put only 4K bytes or 4096 bytes on the have put only 4K bytes or 4096 bytes on the chip.chip.
The 8051 became widely popular after Intel The 8051 became widely popular after Intel allowed other manufacturers to make and allowed other manufacturers to make and market any flavors of the 8051 they please with market any flavors of the 8051 they please with the condition that they remain code-compatible the condition that they remain code-compatible with the 8051. with the 8051.
This has led to many versions of the 8051 with This has led to many versions of the 8051 with different speeds and amounts of on-chip ROM different speeds and amounts of on-chip ROM marketed by more than half a dozen marketed by more than half a dozen manufacturers. manufacturers.
Block Diagram of 8051 µCBlock Diagram of 8051 µC
Features of Intel 8051 µCFeatures of Intel 8051 µC
8052 µC8052 µC 8052 is an advanced 8051.8052 is an advanced 8051. The 8052 an extra 128 bytes of RAM and The 8052 an extra 128 bytes of RAM and
an extra timer. an extra timer.
Therefore, 8052 has 256 bytes of RAM Therefore, 8052 has 256 bytes of RAM and 3 timers. and 3 timers.
It has 8K bytes of on-chip program ROM It has 8K bytes of on-chip program ROM instead of 4K bytes. instead of 4K bytes.
AT89S8253 AT89S8253 µCµC from Atmel Corporation from Atmel Corporation in Dual In-Line (DIP) Packagein Dual In-Line (DIP) Package
Same AT89S8253 Same AT89S8253 µCµC from Atmel from Atmel Corporation in Quad PackageCorporation in Quad Package
AT89S8253 from Atmel AT89S8253 from Atmel CorporationCorporation
The most widely used registers of the The most widely used registers of the 8051 uC are the A, B, R0, R1, R2, R3, 8051 uC are the A, B, R0, R1, R2, R3, R4, R5, R6, R7, DPTR and PCR4, R5, R6, R7, DPTR and PC
All these registers are 8-bits, except All these registers are 8-bits, except DPTR and the program counter which DPTR and the program counter which are 16 bitare 16 bit
COMMON REGISTERS OF THE COMMON REGISTERS OF THE 8051 uC8051 uC
80518051 8-bit Registers or Byte Registers8-bit Registers or Byte Registers
16-bit Registers16-bit Registers
THE A-REGISTER OR THE THE A-REGISTER OR THE ACCUMULATOR REGISTERACCUMULATOR REGISTER
REGISTER A IS CALLED ACCUMULATORREGISTER A IS CALLED ACCUMULATOR
THE ACCUMULATOR IS AN 8-BITS WIDE THE ACCUMULATOR IS AN 8-BITS WIDE REGISTERREGISTER
ACCUMULATOR IS USED FOR ALL ACCUMULATOR IS USED FOR ALL ARITHMETIC AND LOGIC INSTRUCTIONSARITHMETIC AND LOGIC INSTRUCTIONS
MOV instructionMOV instruction MOV destination, source MOV destination, source copies source to destinationcopies source to destination
MOV A,#55HMOV A,#55H ;load value 55H into reg A ;load value 55H into reg A
MOV R0,AMOV R0,A ;copy contents of A into R0 ;copy contents of A into R0 ;(A=R0=55H);(A=R0=55H)
MOV R1,AMOV R1,A ;copy contents of A into R1 ;copy contents of A into R1 ;(A=R0=R1=55H);(A=R0=R1=55H)
MOV R2,AMOV R2,A ;copy contents of A into R2 ;copy contents of A into R2 ;(A=R0=R1=R2=55H);(A=R0=R1=R2=55H)
MOV R3,#95HMOV R3,#95H ;load value 95H into R3 (R3=95H);load value 95H into R3 (R3=95H)
MOV A,R3MOV A,R3 ;copy contents of R3 into A (A=R3=95H);copy contents of R3 into A (A=R3=95H)
Simple InstructionsSimple Instructions
ADD instructionADD instruction ADD A, source ADD A, source ADD the source operand to the ADD the source operand to the
accumulator registeraccumulator register
MOV A,#25HMOV A,#25H ;load 25H into A;load 25H into A
MOV R2,#34HMOV R2,#34H ;load 34H into R2;load 34H into R2
ADD A,R2ADD A,R2 ;add R2 to accumulator;add R2 to accumulator
Executing the program above results Executing the program above results
in A = 59H in A = 59H
ASSEMBLY PROGRAMMING ASSEMBLY PROGRAMMING
Structure of Assembly Language CodeStructure of Assembly Language Code
ORG 0HORG 0H ;start (origin) at 0;start (origin) at 0MOV R5,#25HMOV R5,#25H ;load 25H into R5;load 25H into R5MOV R7,#34HMOV R7,#34H ;load 34H into R7;load 34H into R7MOV A,#0MOV A,#0 ;load 0 into A;load 0 into AADD A,R5ADD A,R5 ;add contents of R5 to A ;add contents of R5 to A
;now A = A + R5;now A = A + R5ADD A,R7ADD A,R7 ;add contents of R7 to A ;add contents of R7 to A
;now A = A + R7;now A = A + R7ADD A, #12HADD A, #12H ;add to A value 12H ;add to A value 12H
;now A = A + 12H ;now A = A + 12H HERE: SJMP HEREHERE: SJMP HERE ;stay in this loop ;stay in this loop ENDEND ;end of asm source file;end of asm source file
Sample Assembly Language ProgramSample Assembly Language Program
ASSEMBLING AND RUNNING ASSEMBLING AND RUNNING AN 8051 PROGRAMAN 8051 PROGRAM
An Assembly language instruction An Assembly language instruction
consists of four fields:consists of four fields:
[[label :label : ] ]mnemonicmnemonic [[operandsoperands] ] [;[;commentcomment] ]
ASSEMBLING AND RUNNING ASSEMBLING AND RUNNING AN 8051 PROGRAMAN 8051 PROGRAM
Steps to Create a Program
PC & ROM SPACE IN 8051PC & ROM SPACE IN 8051
Program counter in the 8051Program counter in the 8051 16 bits wide16 bits wide can access program addresses 0000 to can access program addresses 0000 to
FFFFHFFFFH total of 64K bytes of codetotal of 64K bytes of code
PC & ROM IN 8051PC & ROM IN 8051
Where the 8051 wakes up when it is Where the 8051 wakes up when it is powered up:powered up: wakes up at memory address 0000 when it wakes up at memory address 0000 when it
is powered upis powered up first opcode must be stored at ROM first opcode must be stored at ROM
address 0000Haddress 0000H
PC & ROM IN 8051PC & ROM IN 8051
Placing code in program ROMPlacing code in program ROM the opcode and operand are placed in the opcode and operand are placed in
ROM locations starting at memory 0000ROM locations starting at memory 0000
ROM memory map in the 8051 familyROM memory map in the 8051 family
8051 On-Chip ROM Address Range
PC & ROM IN 8051PC & ROM IN 8051
8051 DATA TYPES AND 8051 DATA TYPES AND DIRECTIVESDIRECTIVES
8051 data type and directives8051 data type and directives
DB (define byte)DB (define byte) ORG (origin)ORG (origin) EQU (equate)EQU (equate) END directiveEND directive
8051 DATA TYPES AND 8051 DATA TYPES AND DIRECTIVESDIRECTIVES
Rules for labels in Assembly languageRules for labels in Assembly language each label name must be uniqueeach label name must be unique first character must be alphabeticfirst character must be alphabetic reserved words must not be used as labels reserved words must not be used as labels
8051 FLAG BITS AND THE 8051 FLAG BITS AND THE PSW REGISTERPSW REGISTER
PSW (program status word) registerPSW (program status word) register
Bits of the PSW Register
8051 FLAG BITS AND THE 8051 FLAG BITS AND THE PSW REGISTERPSW REGISTER
Instructions That Affect Flag Bits
8051 REGISTER BANKS AND 8051 REGISTER BANKS AND STACKSTACK
RAM memory space allocation in the RAM memory space allocation in the 80518051
RAM Allocation in the 8051
8051 REGISTER BANKS AND 8051 REGISTER BANKS AND STACKSTACK
Register banks in the 8051Register banks in the 8051
8051 Register Banks and their RAM Addresses
8051 REGISTER BANKS AND 8051 REGISTER BANKS AND STACKSTACK
How to switch register banksHow to switch register banks
PSW Bits Bank Selection
8051 REGISTER BANKS AND 8051 REGISTER BANKS AND STACKSTACK
Stack in the 8051Stack in the 8051 section of RAM used to store information section of RAM used to store information
temporarilytemporarily could be data or an addresscould be data or an address CPU needs this storage area since there CPU needs this storage area since there
are only a limited number of registersare only a limited number of registers
Part 2Part 2
8051 8051 µCµC DATA DATA PROCESSING PROCESSING INSTRUCTIONS – IINSTRUCTIONS – I
ARITHMETIC ARITHMETIC INSTRUCTIONSINSTRUCTIONS
Arithmetic InstructionsArithmetic Instructions
AddAdd SubtractSubtract IncrementIncrement DecrementDecrement MultiplyMultiply Divide Divide Decimal adjustDecimal adjust
Arithmetic InstructionsArithmetic Instructions
MnemonicMnemonic DescriptionDescription
ADD A, byteADD A, byte add A to byte, put result in Aadd A to byte, put result in A
ADDC A, byteADDC A, byte add with carryadd with carry
SUBB A, byteSUBB A, byte subtract with borrowsubtract with borrow
INC AINC A increment Aincrement A
INC byteINC byte increment byte in memoryincrement byte in memory
INC DPTRINC DPTR increment data pointerincrement data pointer
DEC ADEC A decrement accumulatordecrement accumulator
DEC byteDEC byte decrement bytedecrement byte
MUL ABMUL AB multiply accumulator by b registermultiply accumulator by b register
DIV ABDIV AB divide accumulator by b registerdivide accumulator by b register
DA ADA A decimal adjust the accumulatordecimal adjust the accumulator
ADD InstructionsADD Instructionsadd a, byteadd a, byte ; a ; a a + byte a + byte
addc a, byteaddc a, byte ; a ; a a + byte + C a + byte + C
These instructions affect 3 bits in PSW:These instructions affect 3 bits in PSW:
C = 1 if result of add is greater than FFC = 1 if result of add is greater than FF
AC = 1 if there is a carry out of bit 3AC = 1 if there is a carry out of bit 3
OV = 1 if there is a carry out of bit 7, but not from bit 6, OV = 1 if there is a carry out of bit 7, but not from bit 6, or visa versa.or visa versa.
Instructions that Affect Instructions that Affect PSW bitsPSW bits
ADD ExamplesADD Examples
mov a, #0x3Fmov a, #0x3F
add a, #0xD3add a, #0xD3
What is the value of What is the value of the C, AC, OV flags the C, AC, OV flags after the second after the second instruction is instruction is executed?executed?
0011 1111
1101 0011
0001 0010C = 1
AC = 1
OV = 0
Signed Addition and Signed Addition and OverflowOverflow
0111 1111 (positive 127)
0111 0011 (positive 115)
1111 0010 (overflow cannot represent 242 in 8 bits 2’s complement)
2’s complement:
0000 0000 00 0
…
0111 1111 7F 127
1000 0000 80 -128
…
1111 1111 FF -1
1000 1111 (negative 113)
1101 0011 (negative 45)
0110 0010 (overflow)
0011 1111 (positive)
1101 0011 (negative)
0001 0010 (never overflows)
Addition Example for the Addition Example for the Assembler Assembler
; Computes Z = X + Y; Adds values at locations 0x78 and 0x79 and puts them in location 0x7A; Computes Z = X + Y; Adds values at locations 0x78 and 0x79 and puts them in location 0x7A$INCLUDE (C8051F020.inc)$INCLUDE (C8051F020.inc); EQUATES; EQUATES;-----------------------------------------------------------------------------;-----------------------------------------------------------------------------XX equ equ 0x780x78YY equ equ 0x790x79ZZ equ equ 0x7A0x7A; RESET and INTERRUPT VECTORS; RESET and INTERRUPT VECTORS;-----------------------------------------------------------------------------;----------------------------------------------------------------------------- cseg at 0cseg at 0
ljmp Mainljmp Main; CODE SEGMENT; CODE SEGMENT;-----------------------------------------------------------------------------;-----------------------------------------------------------------------------
cseg at 100hcseg at 100hMain: Main: mov 0xFF, #0DEhmov 0xFF, #0DEh ; Disable watchdog timer ; Disable watchdog timer mov 0xFF, #0ADhmov 0xFF, #0ADh
mov a, Xmov a, Xadd a, Yadd a, Ymov Z, amov Z, anopnopendend
Subtract Subtract
SUBB A, byteSUBB A, byte subtract with borrowsubtract with borrow
Example:
SUBB A, #0x4F ; A A – 4F – C
Notice that there is no subtraction WITHOUT borrow. Therefore, ifa subtraction without borrow is desired, it is necessary to clear the Cflag.
Increment and Increment and DecrementDecrement
The increment and decrement instructions do The increment and decrement instructions do NOT affect the C flag.NOT affect the C flag.
Notice we can only INCREMENT the data Notice we can only INCREMENT the data pointer, not decrement.pointer, not decrement.
INC AINC A increment Aincrement A
INC byteINC byte increment byte in memoryincrement byte in memory
INC DPTRINC DPTR increment data pointerincrement data pointer
DEC ADEC A decrement accumulatordecrement accumulator
DEC byteDEC byte decrement bytedecrement byte
Example: Increment 16-Example: Increment 16-bit Wordbit Word Clearly we have to take the word Clearly we have to take the word
in 2 8-bit long registersin 2 8-bit long registers Assume 16-bit word in R3:R2Assume 16-bit word in R3:R2
mov a, r2 mov a, r2 add a, #1 add a, #1 ; use add rather than increment to ; use add rather than increment to
affect C affect C mov r2, a mov r2, a mov a, r3 mov a, r3 addc a, #0 addc a, #0 ; add C to most significant byte; add C to most significant bytemov r3, a mov r3, a
MultiplyMultiply
When multiplying two 8-bit numbers, the When multiplying two 8-bit numbers, the size of the maximum product is 16-bitssize of the maximum product is 16-bits
FF x FF = FE01FF x FF = FE01
(255 x 255 = 65025)(255 x 255 = 65025)
MUL AB ; BA A * B
Note: B gets the HIGH byte, A gets the LOW byte
DivisionDivision
Integer DivisionInteger Division
DIV ABDIV AB ; divide A by B; divide A by B
A A Quotient(A/B), B Quotient(A/B), B Remainder(A/B) Remainder(A/B)
OV - used to indicate a divide by zero condition.OV - used to indicate a divide by zero condition.C – set to zeroC – set to zero
Decimal AdjustDecimal Adjust
DA aDA a ; decimal adjust a; decimal adjust a
Used to facilitate BCD addition. Adds “6” to either high or Used to facilitate BCD addition. Adds “6” to either high or low nibble after an addition to create a valid BCD low nibble after an addition to create a valid BCD number.number.
Example:Example:mov a, #0x23mov a, #0x23mov b, #0x29mov b, #0x29add a, badd a, b ; a ; a 23 + 29 = 4C (wanted 23 + 29 = 4C (wanted
52)52)DA aDA a ; a ; a a + 6 = 52 a + 6 = 52
Note: This instruction does NOT convert binary to BCD!Note: This instruction does NOT convert binary to BCD!
Part 3Part 3
8051 8051 µCµC DATA DATA PROCESSING PROCESSING INSTRUCTIONS – IIINSTRUCTIONS – II
LOGIC INSTRUCTIONSLOGIC INSTRUCTIONS
Logic InstructionsLogic InstructionsBitwise logic operations (AND, OR, XOR, NOT)Bitwise logic operations (AND, OR, XOR, NOT)
ClearClear
RotateRotate
SwapSwap
Logic instructions do NOT affect the flags in PSWLogic instructions do NOT affect the flags in PSW
Bitwise LogicBitwise Logic
ANL – AND ANL – AND
ORL – OR ORL – OR
XRL – eXclusive ORXRL – eXclusive OR
CPL – ComplementCPL – Complement
Examples:0000111110101100ANL
0000111110101100ORL
0000111110101100XRL
10101100CPL
00001100
10101111
10100011
01010011
Address Modes with Address Modes with LogicLogic
a, bytea, bytedirect, reg. indirect, reg, direct, reg. indirect, reg, immediateimmediate
byte, abyte, adirectdirect
byte, #constantbyte, #constant
a ex: cpl aa ex: cpl a
ANL – AND
ORL – OR
XRL – eXclusive oR
CPL – Complement
Uses of Logic InstructionsUses of Logic Instructions
Force individual bits low, without affecting other bits.Force individual bits low, without affecting other bits.anl PSW, #0xE7anl PSW, #0xE7 ;PSW AND 11100111;PSW AND 11100111anl PSW, #11100111banl PSW, #11100111b ; can use “binary”; can use “binary”
Force individual bits high.Force individual bits high.orl PSW, #0x18orl PSW, #0x18 ;PSW OR 00011000;PSW OR 00011000
Complement individual bitsComplement individual bitsxrl P1, #0x40xrl P1, #0x40 ;P1 XRL 01000000;P1 XRL 01000000
Other Logic InstructionsOther Logic Instructions
CLR - clearCLR - clear RL – rotate leftRL – rotate left RLC – rotate left through CarryRLC – rotate left through Carry RR – rotate rightRR – rotate right RRC – rotate right through CarryRRC – rotate right through Carry SWAP – swap accumulator nibblesSWAP – swap accumulator nibbles
CLR – Set all bits to 0CLR – Set all bits to 0
CLR ACLR A
CLR byteCLR byte (direct mode)(direct mode)
CLR RiCLR Ri (register mode)(register mode)
CLR @RiCLR @Ri (register indirect mode)(register indirect mode)
RotateRotate
Rotate instructions operate only on Rotate instructions operate only on aa
rl arl a
mov a, #0xF0mov a, #0xF0 ; a; a 11110000 11110000
rl arl a ; a; a 11100001 11100001
Rotate through CarryRotate through Carry
rrc arrc a
mov a, #0A9hmov a, #0A9h ; a ; a A9 A9
add a, #14hadd a, #14h ; a ; a BD (10111101), C BD (10111101), C00
rrc arrc a ; a ; a 01011110, C01011110, C11
C
SwapSwap
swap aswap a
mov a, #72hmov a, #72h
swap aswap a ; a ; a 27h 27h
Bit Logic OperationsBit Logic Operations
Some logic operations can be used with single bit Some logic operations can be used with single bit operandsoperands
ANL C, bitANL C, bit ANL C, /bit ANL C, /bitORL C, bitORL C, bit ORL C, /bit ORL C, /bitCLR CCLR CCLR bitCLR bitCPL CCPL CCPL bitCPL bitSETB CSETB CSETB bitSETB bit
“bit” can be any of the bit-addressable RAMlocations or SFRs.
Rotate and Rotate and Multiplication/DivisionMultiplication/Division
Note that a shift left is the same as Note that a shift left is the same as multiplying by 2, shift right is divide by 2multiplying by 2, shift right is divide by 2
mov a, #3mov a, #3 ; A; A 00000011 (3) 00000011 (3)
clr Cclr C ; C; C 0 0
rlc arlc a ; A; A 00000110 (6) 00000110 (6)
rlc arlc a ; A; A 00001100 (12) 00001100 (12)
rrc arrc a ; A; A 00000110 (6) 00000110 (6)
Shift/Multiply ExampleShift/Multiply Example
Program segment to multiply by 2 and Program segment to multiply by 2 and add 1 add 1
clr cclr c
rl arl a ;multiply by 2;multiply by 2
inc ainc a ;and add one;and add one
Part 4Part 4
JUMP AND JUMP AND LOOP LOOP INSTRUCTIONSINSTRUCTIONS
LOOP AND JUMP LOOP AND JUMP INSTRUCTIONSINSTRUCTIONS
Repeating a sequence of instructions a certain number Repeating a sequence of instructions a certain number of times is called a loop.of times is called a loop.
The loop action is performed by the instruction The loop action is performed by the instruction DJNZ reg, labelDJNZ reg, label..
In this instruction, the register is decremented; if it is In this instruction, the register is decremented; if it is not zero, it jumps to the target address referred to by not zero, it jumps to the target address referred to by the label. the label.
Prior to the start of the loop the register is loaded with Prior to the start of the loop the register is loaded with the counter for the number the counter for the number of of repetitions. repetitions.
In this instruction both the register decrement and the In this instruction both the register decrement and the decision to jump arc combined into a single instruction.decision to jump arc combined into a single instruction.
The registers can be any of R0 - R7. The counter can The registers can be any of R0 - R7. The counter can also be a RAM locationalso be a RAM location
LOOP AND JUMP LOOP AND JUMP INSTRUCTIONSINSTRUCTIONS
LOOP AND JUMP LOOP AND JUMP INSTRUCTIONSINSTRUCTIONS
Looping in the 8051Looping in the 8051 Problem 1Problem 1
In the 8051, looping action with the instruction In the 8051, looping action with the instruction "DJNZ Rx, rel address" is limited to _______ "DJNZ Rx, rel address" is limited to _______ iterations.iterations.
Answer : Answer : 256256 Problem 2Problem 2
If a conditional jump is not taken, what is the If a conditional jump is not taken, what is the next instruction to be executed?next instruction to be executed?
Answer : Answer : the instruction following the jumpthe instruction following the jump
LOOP AND JUMP LOOP AND JUMP INSTRUCTIONSINSTRUCTIONS
SJMP to itself using $ signSJMP to itself using $ sign Problem 3Problem 3
In calculating the target address for a jump, a In calculating the target address for a jump, a displacement is added to the contents of displacement is added to the contents of register ___________ .register ___________ .
Answer: Answer: PCPC Problem 3Problem 3
The mnemonic SJMP stands for __________ The mnemonic SJMP stands for __________ and it is a ____ - byte instruction.and it is a ____ - byte instruction.
Answer: Answer: short jump , 2short jump , 2
Loop inside a loopLoop inside a loop
What happens if we want to repeat an action more times than What happens if we want to repeat an action more times than
256?256?
Write a program to (a) load the accumulator with the value 55H, Write a program to (a) load the accumulator with the value 55H,
and (b) complement the ACC 700 times.and (b) complement the ACC 700 times.
Since 700 is larger than 255 (the maximum capacity of any register), Since 700 is larger than 255 (the maximum capacity of any register),
we use two registers to hold the count. The following code shows how we use two registers to hold the count. The following code shows how
to use R2 and R3 for the count.to use R2 and R3 for the count.
MOV A,#55H MOV A,#55H ;A=55H;A=55H
NEXT:NEXT: MOV R3,#10MOV R3,#10 ;R3=10, the outer loop count;R3=10, the outer loop count
AGAIN:AGAIN: MOV R2,#70MOV R2,#70 ;R2=70, the inner loop count;R2=70, the inner loop count
CPL ACPL A ;complement;complement
LOOP AND JUMP LOOP AND JUMP INSTRUCTIONSINSTRUCTIONS
Other conditional jumpsOther conditional jumps
Other conditional jumps Other conditional jumps
JZ (jump if A = 0) JZ (jump if A = 0) In this instruction the content of register A is In this instruction the content of register A is
checked. If it is zero, it jumps to the target checked. If it is zero, it jumps to the target address.address.
JZ instruction can be used only for register A. JZ instruction can be used only for register A. It can only check to see whether the It can only check to see whether the
accumulator is zero, and it does not apply to accumulator is zero, and it does not apply to any other register. any other register.
Don't have to perform an arithmetic instruction Don't have to perform an arithmetic instruction such as decrement to use the JZ instruction. such as decrement to use the JZ instruction.
Other conditional jumpsOther conditional jumps
JNZ (jump if A JNZ (jump if A 0) 0) In this instruction the content of register A is In this instruction the content of register A is
checked. If it is not zero, it jumps to the checked. If it is not zero, it jumps to the target address.target address.
Other conditional jumpsOther conditional jumps
JNC Jump JNC Jump if if no no carry, jumps carry, jumps if CY = 0)if CY = 0) carry flag bit in the flag (PSW) register is carry flag bit in the flag (PSW) register is
used to make the decision whether to jumpused to make the decision whether to jump "JNC label", the processor looks at the carry "JNC label", the processor looks at the carry
flag to see if it is raised (CY = 1). flag to see if it is raised (CY = 1). if it is not, the CPU starts to fetch and if it is not, the CPU starts to fetch and
execute instructions from the address of the execute instructions from the address of the label. label.
if CY = 1, it will not jump but will execute the if CY = 1, it will not jump but will execute the next instruction below JNC.next instruction below JNC.
Other conditional jumpsOther conditional jumps
JC Jump JC Jump if if carry, jumps carry, jumps if CY = 1)if CY = 1) if CY = l it jumps to the target addressif CY = l it jumps to the target address
JB (jump if bit is high)JB (jump if bit is high) JNB (jump if bit is low)JNB (jump if bit is low)
LOOP AND JUMP LOOP AND JUMP INSTRUCTIONSINSTRUCTIONS
All conditional jumps are short jumpsAll conditional jumps are short jumps
Table 3–1 8051 Conditional Jump Instructions
Unconditional jump Unconditional jump instructionsinstructions
There are two unconditional jumps: There are two unconditional jumps: LJMP LJMP (long jump) and (long jump) and SJMP SJMP (short jump).(short jump).
LJMP is 3-byte instruction in which the first LJMP is 3-byte instruction in which the first byte is the op-code, and the second and third byte is the op-code, and the second and third bytes represent the 16-bit address of the target bytes represent the 16-bit address of the target location.location.
The 2-byte target address allows a jump to any The 2-byte target address allows a jump to any memory loca tion from 0000 to FFFFH. memory loca tion from 0000 to FFFFH.
Unconditional jump Unconditional jump instructionsinstructions
SJMP (short jump)SJMP (short jump) 2-byte instruction, the first byte is the op-code and the 2-byte instruction, the first byte is the op-code and the
second byte is the relative address of the target second byte is the relative address of the target location. location.
The relative address range of 00 – FFH is divided into The relative address range of 00 – FFH is divided into forward and backward jumps; that is, within -128 to forward and backward jumps; that is, within -128 to +127 bytes of memory relative to the address of the +127 bytes of memory relative to the address of the current PC (program counter). current PC (program counter).
If the jump is forward, the target address can be If the jump is forward, the target address can be within a space of 127 bytes from the current PC. within a space of 127 bytes from the current PC.
If the target address is backward, the target address If the target address is backward, the target address can be within -128 bytes from the current PC.can be within -128 bytes from the current PC.
Calculating the short jump Calculating the short jump addressaddress
Using the following list tile, verify the jump forward address calculation.Using the following list tile, verify the jump forward address calculation.
Line Line PCPC Op-codeOp-code Mnemonic Mnemonic OperandOperand11 00000000 ORG 0000ORG 00002 2 00000000 78007800 MOV R0, MOV R0, #003 #003 33 00020002 74557455 MOV A,MOV A, #55H0#55H04 4 0004 0004 60036003 JZ NEXTJZ NEXT5 5 00060006 0808 INC R0INC R06 6 00070007 0404 AGAIN:AGAIN: INC AINC A7 7 00080008 0404 INC AINC A8 8 00090009 24772477 NEXT:NEXT: ADD A,ADD A, #77h#77h9 9 000B000B 50055005 JNC OVERJNC OVER1010 000D 000D E4E4 CLR ACLR A11 11 000E000E F8F8 MOV R0, AMOV R0, A12 12 000F000F F9F9 MOV R1, AMOV R1, A13 13 00100010 FAFA MOV R2, AMOV R2, A14 14 00110011 FBFB MOV R3, AMOV R3, A15 15 00120012 2B2B OVER:OVER: ADD A, R3ADD A, R316 16 00130013 50F250F2 JNC AGAINJNC AGAIN1717 00150015 80FE80FE HERE:HERE: SJMP HERESJMP HERE
18 18 00170017 ENDEND
Calculating the short jump Calculating the short jump addressaddress
Part 5Part 5
CALL CALL INSTRUCTIONSINSTRUCTIONS
CALL INSTRUCTIONSCALL INSTRUCTIONS
CALL is used to call a subroutine. CALL is used to call a subroutine. Subroutines are often used to perform tasks Subroutines are often used to perform tasks
that need to be performed frequently. that need to be performed frequently. This makes a program more structured in This makes a program more structured in
addition to saving memory space. addition to saving memory space. There are two instructions : LCALL (long call) There are two instructions : LCALL (long call)
and ACALL (absolute call). and ACALL (absolute call). Deciding which one to use depends on the Deciding which one to use depends on the
target address. target address.
CALL INSTRUCTIONSCALL INSTRUCTIONS
LCALL (long call)LCALL (long call) 3-byte instruction, the first byte is the op-code and the second and 3-byte instruction, the first byte is the op-code and the second and
third bytes are used for the address of the target subroutine.third bytes are used for the address of the target subroutine. LCALL can be used to call subroutines located anywhere within LCALL can be used to call subroutines located anywhere within
the 64K-byte address space of the 8051. the 64K-byte address space of the 8051. To make sure that after execution of the called subroutine the To make sure that after execution of the called subroutine the
8051 knows where to come back to, the processor automatically 8051 knows where to come back to, the processor automatically saves on the stack the address of the instruction immediately saves on the stack the address of the instruction immediately below the LCALL. below the LCALL.
When a subroutine is called, control is transferred to that When a subroutine is called, control is transferred to that subroutine, and the processor saves the PC (program counter) on subroutine, and the processor saves the PC (program counter) on the stack and begins to fetch instructions from the new location.the stack and begins to fetch instructions from the new location.
After finishing execution of the subroutine, the instruction RET After finishing execution of the subroutine, the instruction RET (return) transfers control back to the caller. Every subroutine (return) transfers control back to the caller. Every subroutine needs RET as the last instruction.needs RET as the last instruction.
CALL INSTRUCTIONSCALL INSTRUCTIONS
LCALL (long call)LCALL (long call)
Figure 3–1 8051 Assembly Main Program That Calls Subroutines
CALL INSTRUCTIONSCALL INSTRUCTIONS
Part 6Part 6
TIMING TIMING CALCULATIONSCALCULATIONS
TIME DELAY FOR TIME DELAY FOR VARIOUS 8051 CHIPSVARIOUS 8051 CHIPS
Machine cycle for the 8051Machine cycle for the 8051 The MCU takes a certain number of clock cycles to The MCU takes a certain number of clock cycles to
execute an instruction. execute an instruction. These clock cycles are referred to as These clock cycles are referred to as machine cycles. machine cycles. In the 8051 family, the length of the machine cycle In the 8051 family, the length of the machine cycle
depends on the frequency of the crystal oscillator.depends on the frequency of the crystal oscillator. The frequency of the crystal connected to the 8051 The frequency of the crystal connected to the 8051
family can vary from 4 MHz to 30 MHz.family can vary from 4 MHz to 30 MHz. In the original 8051, one machine cycle lasts 12 In the original 8051, one machine cycle lasts 12
oscillator periods. oscillator periods. Therefore, to calculate the machine cycle for the 8051, Therefore, to calculate the machine cycle for the 8051,
we take 1/12 of the crystal frequency, then take its we take 1/12 of the crystal frequency, then take its inverse.inverse.
TIME DELAY FOR TIME DELAY FOR VARIOUS 8051 CHIPSVARIOUS 8051 CHIPS
Machine cycle for the 8051Machine cycle for the 8051
Clocks per Machine Cycle (MC) for Various 8051 Versions
TIME DELAY FOR TIME DELAY FOR VARIOUS 8051 CHIPSVARIOUS 8051 CHIPS
Delay calculation for other versions of Delay calculation for other versions of 80518051
Table 3–3 Comparison of 8051 and DS89C4x0 Machine Cycles
TIME DELAY FOR TIME DELAY FOR VARIOUS 8051 CHIPSVARIOUS 8051 CHIPS
Part 7Part 7
8051 I/O PORT 8051 I/O PORT PROGRAMMINGPROGRAMMING
WHAT ARE I/O PORTS?WHAT ARE I/O PORTS? I/O Ports are basically the interfaces which I/O Ports are basically the interfaces which
connect the 8051 uC to external devicesconnect the 8051 uC to external devices
After basic connection, that is, after setting up After basic connection, that is, after setting up the hardware connection, I/O ports can read, the hardware connection, I/O ports can read, that is, receive data from those devices and can that is, receive data from those devices and can also write, that is, send data to themalso write, that is, send data to them
Inputs can be read/received from ports and Inputs can be read/received from ports and outputs can be written/sent to the I/O ports by outputs can be written/sent to the I/O ports by writing suitable programs for the 8051 uC.writing suitable programs for the 8051 uC.
This is a very useful function because the This is a very useful function because the 8051 uC can then be used for monitoring 8051 uC can then be used for monitoring real world processes as we see in digital real world processes as we see in digital instruments where different parameters instruments where different parameters like Pressure, Temperature, Speed of like Pressure, Temperature, Speed of Rotation, etc can be acquired and Rotation, etc can be acquired and displayeddisplayed
This is also very useful because This is also very useful because microcontrollers have data processing microcontrollers have data processing capability (though limited) which can be capability (though limited) which can be used for processing these signals through used for processing these signals through programs (which we write), and based on programs (which we write), and based on the result perform some control function by the result perform some control function by sending data to the device through the sending data to the device through the output ports or pins of the microcontroller.output ports or pins of the microcontroller.
So for example, we can use the input port/pin of So for example, we can use the input port/pin of the 8051 uC to keep reading the temperature of the 8051 uC to keep reading the temperature of an oven, and when the temperature exceeds a an oven, and when the temperature exceeds a certain value, we can use the output port/pin of certain value, we can use the output port/pin of the 8051 uC to either turn-off the switch of the the 8051 uC to either turn-off the switch of the oven automatically or to activate a sound alarm oven automatically or to activate a sound alarm (for manual intervention) and to once again turn (for manual intervention) and to once again turn it on when the temperature falls below a it on when the temperature falls below a specified value or to activate a sound alarm.specified value or to activate a sound alarm.
ANALOGY OF PORTSANALOGY OF PORTS We have got sea ports, air ports, bus ports (what are We have got sea ports, air ports, bus ports (what are
called bus terminals) and rail ports (railway stations) in a called bus terminals) and rail ports (railway stations) in a city.city.
These ports are used for connecting the city with the rest These ports are used for connecting the city with the rest of the world for bringing people and cargo inside the city of the world for bringing people and cargo inside the city (Input Port)(Input Port)
They are also used for sending people and cargo outside They are also used for sending people and cargo outside the city (Output Port)the city (Output Port)
Generally we do not see separate physical ports in cities Generally we do not see separate physical ports in cities for Input and Output Functionsfor Input and Output Functions
Now this analogy pretty much applies for the 8051 uC as Now this analogy pretty much applies for the 8051 uC as wellwell
4 I/O Ports in the 8051 are like the 4 4 I/O Ports in the 8051 are like the 4 railway stations of a big cityrailway stations of a big city
Individual Pins are like Platforms of the Individual Pins are like Platforms of the
Railway StationRailway Station
You got 8 platforms (pins) per I/O port in You got 8 platforms (pins) per I/O port in 8051!8051!
8051 Pin Diagram
8051 I/O PORT 8051 I/O PORT PROGRAMMINGPROGRAMMING You have got 4 I/O ports in the 8051 uC. They are You have got 4 I/O ports in the 8051 uC. They are
named as P0, P1, P2, and P3.named as P0, P1, P2, and P3.
You have to always keep in mind that each of these 4 You have to always keep in mind that each of these 4 ports have 8 pins each. ports have 8 pins each.
Individual pins of these ports are named as P0.1, Individual pins of these ports are named as P0.1, P0.2, P0.3, and so on (Port 0 Platform No.1, Port 0 P0.2, P0.3, and so on (Port 0 Platform No.1, Port 0 Platform No.2, and so on)Platform No.2, and so on)
When you When you RESETRESET the 8051 uC then all the ports of the 8051 uC then all the ports of the 8051 are configured as input ports, and are ready the 8051 are configured as input ports, and are ready to read data, that is, take data inside, that is, all to read data, that is, take data inside, that is, all stations and all platforms of the stations are ready stations and all platforms of the stations are ready for receiving incoming trains!for receiving incoming trains!
8051 I/O PORT 8051 I/O PORT PROGRAMMINGPROGRAMMING
And how do you reset the 8051 uC? And how do you reset the 8051 uC?
This is done by holding the RST pin (pin no. 9 This is done by holding the RST pin (pin no. 9 in the 8051 pin diagram) at Logic 1 for 2 in the 8051 pin diagram) at Logic 1 for 2 consecutive machine cycles.consecutive machine cycles.
In practice, it means that you apply the voltage In practice, it means that you apply the voltage level corresponding to Logic 1 (+5V) to the level corresponding to Logic 1 (+5V) to the RST pin of the 8051 uC for a very short time RST pin of the 8051 uC for a very short time interval corresponding to 2 machine cycles of interval corresponding to 2 machine cycles of the 8051 uC.the 8051 uC.
8051 I/O PORT 8051 I/O PORT PROGRAMMINGPROGRAMMING
When you write the first 0 to a port, then that port When you write the first 0 to a port, then that port becomes an output port and can be used for writing becomes an output port and can be used for writing data or sending data outside.data or sending data outside.
For reconfiguring (phir se configuring ya dobara se For reconfiguring (phir se configuring ya dobara se configuring) the port (which you have made output configuring) the port (which you have made output port) as an input port, you have to move 1 to that port) as an input port, you have to move 1 to that port.port.
For using any of these 4 uC ports for data input or For using any of these 4 uC ports for data input or output, you have to write programs in Assembly or C output, you have to write programs in Assembly or C language.language.
Port 0Port 0 You can use this port as either an input port or an You can use this port as either an input port or an
output port.output port.
Before using port 0 as an input or an output port, Before using port 0 as an input or an output port, you have to connect you have to connect each pineach pin of port 0 to 10 Kilo of port 0 to 10 Kilo ohm resistors as shown in the diagram on next slide.ohm resistors as shown in the diagram on next slide.
This is because the port P0 has no internal resistors. This is because the port P0 has no internal resistors.
The other ports P1, P2, and P3 have internal or built-The other ports P1, P2, and P3 have internal or built-in resistors on the 8051 chip itself.in resistors on the 8051 chip itself.
So external resistors should not be connected to the So external resistors should not be connected to the pins of P1, P2, and P3 ports.pins of P1, P2, and P3 ports.
8051 I/O PROGRAMMING8051 I/O PROGRAMMING
Port Port 00
Port 0 with External Resistors
Port 0 as inputPort 0 as input After connecting 10Kohm external After connecting 10Kohm external
resistors to all pins of port 0resistors to all pins of port 0, , in the in the manner shown earlier, in order manner shown earlier, in order to make to make port 0 an input portport 0 an input port, the port must be , the port must be programmed by programmed by writing 1 to all its bitswriting 1 to all its bits. .
Dual role of port 0 Dual role of port 0
Port Port 0 0 is also designated as AD0 - is also designated as AD0 - AD7, allowing it to be used for both AD7, allowing it to be used for both address and data.address and data.
When connecting an 8051/31 to an When connecting an 8051/31 to an external memory, port 0 provides both external memory, port 0 provides both address and data. address and data.
The 8051 multiplexes address and The 8051 multiplexes address and data through port 0 to save pins.data through port 0 to save pins.
8051 I/O PROGRAMMING8051 I/O PROGRAMMING
Port 1Port 1 It can be used as input or output. It can be used as input or output. This port does not need any resistors This port does not need any resistors
since it already has resistors since it already has resistors internally. internally.
Upon reset, port I is configured as an Upon reset, port I is configured as an input port. input port.
Port 1 as input Port 1 as input
If port 1 has been configured as an If port 1 has been configured as an output port, to make it an input port output port, to make it an input port again, it must programmed as such by again, it must programmed as such by writing 1 to all its bits. writing 1 to all its bits.
Port 1 as inputPort 1 as input
In the following code, port 1 is configured first as In the following code, port 1 is configured first as an input port by writing 1 s to it, then data is an input port by writing 1 s to it, then data is received from that port and saved in R7, R6, and received from that port and saved in R7, R6, and
R5.R5.
DELAY SUBROUTINEDELAY SUBROUTINE
..
..MOV R0, #30HMOV R0, #30H....ORG 300HORG 300HDELAY: NOPDELAY: NOPAGAIN: DJNZ R0, AGAINAGAIN: DJNZ R0, AGAINRETRETENDEND
Port Port 22
Port 2 occupies a total of 8 pins (pins 21 Port 2 occupies a total of 8 pins (pins 21 through 28). through 28).
It can be used as input or output. It can be used as input or output.
Port Port 2 2 does not need any external resistors does not need any external resistors since it already has external resistors since it already has external resistors internally. internally.
Upon reset, port 2 is configured as an input Upon reset, port 2 is configured as an input port. port.
Port 2 as inputPort 2 as input
To make port 2 an input, it must programmed as To make port 2 an input, it must programmed as such by writing 1 to all its bits. such by writing 1 to all its bits.
In the following code, port 2 is configured first as In the following code, port 2 is configured first as an input port by writing is to it. an input port by writing is to it.
Dual role of port 2Dual role of port 2
In 8031-based systems, port 2 must be used along with In 8031-based systems, port 2 must be used along with P0 to provide the 16-bit address for external memory. P0 to provide the 16-bit address for external memory.
Port 2 is also designated as A8 - A15, indicating its dual Port 2 is also designated as A8 - A15, indicating its dual function. function.
Since an 8051/31 is capable of accessing 64K bytes of Since an 8051/31 is capable of accessing 64K bytes of external memory, it needs a path for the 16 bits of the external memory, it needs a path for the 16 bits of the address. address.
P0 provides the lower 8 bits via AD0 - AD7P0 provides the lower 8 bits via AD0 - AD7 P2 provides bits A8 - A 15 of the address. P2 provides bits A8 - A 15 of the address. When the 8051 /31 is connected to external memory, P2 When the 8051 /31 is connected to external memory, P2
is used for the upper 8 bits of the 16-bit address, and it is used for the upper 8 bits of the 16-bit address, and it cannot be used for I/O. cannot be used for I/O.
Port 3Port 3
Port 3 can be used as input or output. Port 3 can be used as input or output. P3 does not need any external resistors. P3 does not need any external resistors. Port 3 is configured as an input port upon Port 3 is configured as an input port upon
reset. reset. Port 3 has the additional function of Port 3 has the additional function of
providing some extremely important providing some extremely important signals such as interrupts, serial I/O, signals such as interrupts, serial I/O, timer/counter and read/write control for timer/counter and read/write control for external memory. external memory.
Port 3Port 3
Port 3 Alternate Functions
Different ways of toggling the entire 8 Different ways of toggling the entire 8 bitsbits
Different ways of toggling Different ways of toggling the entire 8 bitsthe entire 8 bits
Ports status upon resetPorts status upon reset
Reset Value of Some 8051 Ports
PROGRAMMING INDIVIDUAL PROGRAMMING INDIVIDUAL I/O PINS BY BIT I/O PINS BY BIT MANIPULATIONMANIPULATION
A powerful feature of 80511/0 ports is their A powerful feature of 80511/0 ports is their capability to access individual bits of the port capability to access individual bits of the port without altering the rest of the bits in that port. without altering the rest of the bits in that port.
Of the four 8051 ports, we can access either the Of the four 8051 ports, we can access either the entire 8 bits or any single bit without altering the entire 8 bits or any single bit without altering the rest. rest.
"SETB X. Y" where X is the port number 0, 1, 2, or "SETB X. Y" where X is the port number 0, 1, 2, or 3, and Y is the desired bit number from 0 to 7 for 3, and Y is the desired bit number from 0 to 7 for data bits DO to D7. data bits DO to D7.
"SETB P1.5" sets bit 5 of port 1 high."SETB P1.5" sets bit 5 of port 1 high.
The following code toggles bit P1.2 The following code toggles bit P1.2 continuously. continuously.
I/O ports and bit-addressabilityI/O ports and bit-addressability
Single-Bit Addressability of Ports
I/O BIT MANIPULATION I/O BIT MANIPULATION PROGRAMMINGPROGRAMMING
I/O ports and bit-addressabilityI/O ports and bit-addressability
Table 4–4 Single-Bit Instructions
I/O BIT MANIPULATION I/O BIT MANIPULATION PROGRAMMINGPROGRAMMING
Checking an input bitChecking an input bit
Instructions For Reading an Input Port
Reading a single bit into the Reading a single bit into the carry flagcarry flag
Reading input pins vs. port Reading input pins vs. port latchlatch
Some instructions read the contents of a Some instructions read the contents of a port, modify its value, and write it back. port, modify its value, and write it back. (READ-MODIFY-WRITE)(READ-MODIFY-WRITE)
F.E. ANL P1, AF.E. ANL P1, A Reads internal port latch & brings it to Reads internal port latch & brings it to
CPUCPU Data is ANDed with contents of AData is ANDed with contents of A Result is rewritten to port latchResult is rewritten to port latch Port Pin Data = Port LatchPort Pin Data = Port Latch
Instructions for reading Instructions for reading input portsinput ports
To make any bit of any 8051 port an To make any bit of any 8051 port an input port, we must write 1 (logic high) input port, we must write 1 (logic high) to that bit. to that bit.
After we configure the port bits as After we configure the port bits as input, we can use only certain input, we can use only certain instructions in order to get the instructions in order to get the external data present at the pins into external data present at the pins into the CPU.the CPU.
Pin & LatchPin & Latch
Port PinsPort Pins Current state of Current state of portport pin pin Reading from Port: Data is read directly from Reading from Port: Data is read directly from portport
pins in case the port is configured as input.pins in case the port is configured as input. Writing to Port: Writes to an internal register (called Writing to Port: Writes to an internal register (called
latch reglatch reg) which is reflected to pin if ) which is reflected to pin if portport is is configured as output.configured as output.
LatchLatch To write data on To write data on portport Data will be reflected/moved to Data will be reflected/moved to portport pin if configured pin if configured
as o/p, and will have no effect incase of i/p.as o/p, and will have no effect incase of i/p.
Reading latch for output portReading latch for output port
Instructions Reading a Latch (Read-Modify-Write)
Read-modify-write featureRead-modify-write feature
The ports in the 8051 can be accessed The ports in the 8051 can be accessed by the read-modify-write technique. by the read-modify-write technique. (1) reading the port (1) reading the port (2) modifying its value (2) modifying its value (3) writing to the port (3) writing to the port
Sample ProgramsSample Programs Toggle all bits of P0, P1, and P2 every ¼ sec Toggle all bits of P0, P1, and P2 every ¼ sec
assuming crystal frequency of 11.0592 MHzassuming crystal frequency of 11.0592 MHz
Main thing here is the delay loopMain thing here is the delay loop 50% & 66% duty cycle square waves on P1.050% & 66% duty cycle square waves on P1.0 Monitor P0.1 till it is highMonitor P0.1 till it is high
When high, read data from port 1When high, read data from port 1 Low to High Pulse on P0.2 when this happensLow to High Pulse on P0.2 when this happens
P2.3 represents oven conditionP2.3 represents oven condition If high, oven is hot If high, oven is hot high to low pulse on P1.5 to activate buzzerhigh to low pulse on P1.5 to activate buzzer
Sample ProgramsSample Programs
60% duty cycle sq waveform60% duty cycle sq waveform
SETB P1.3SETB P1.3
LCALL DELAYLCALL DELAY
LCALL DELAYLCALL DELAY
CLR P1.3CLR P1.3
LCALL DELAYLCALL DELAY
SJMP BACKSJMP BACK
OvenOven
HERE JNB 2.3 HEREHERE JNB 2.3 HERE
SETB P1.5SETB P1.5
CLR P1.5CLR P1.5
SJMP HERESJMP HERE
SWITCH STATUSSWITCH STATUS
SETB P1.7SETB P1.7
AGAIN: JB P1.2 OVERAGAIN: JB P1.2 OVER
MOV P2, #’N’MOV P2, #’N’
SJMP AGAINSJMP AGAIN
OVER: MOV P2, #’Y’OVER: MOV P2, #’Y’
SJMP AGAINSJMP AGAIN
SWITCH TO P0.1SWITCH TO P0.1CHECK SWITCHCHECK SWITCHSWITCH =1 THEN HIGH TO LOW TO SWITCH =1 THEN HIGH TO LOW TO ACTIVATE SIREN ON P1.7ACTIVATE SIREN ON P1.7
SETB P0.1SETB P0.1AGAIN: MOV C, P0.1AGAIN: MOV C, P0.1JNC AGAINJNC AGAINSETB P1.7SETB P1.7CLR P1.7CLR P1.7SJMP AGAINSJMP AGAIN
SWITCH TO P1.0SWITCH TO P1.0
LED TO P2.7LED TO P2.7
SWITCH STATUS SEND TO LEDSWITCH STATUS SEND TO LED
SETB P1.7SETB P1.7
AGAIN: MOV C, P1.0AGAIN: MOV C, P1.0
MOV P2.7, CMOV P2.7, C
SJMP AGAINSJMP AGAIN
Instructions vs. Instructions vs. DirectivesDirectives
Assembler DirectivesAssembler Directives Instructions for the ASSEMBLERInstructions for the ASSEMBLER NOT 8051 instructionsNOT 8051 instructions
Examples:Examples:;;cseg stands for “code segment”cseg stands for “code segment”
cseg atcseg at 1000h 1000h ;address of next ;address of next instruction instruction is 1000his 1000h
GREEN_LED GREEN_LED equequ P1.6 P1.6 ;symbol for Port 1, bit 6;symbol for Port 1, bit 6
Assembler DirectivesAssembler Directives DATADATA
Used to define a name for memory locationsUsed to define a name for memory locationsSP DATA 0x81 ;special function registersSP DATA 0x81 ;special function registersMY_VAL DATA 0x44 ;RAM locationMY_VAL DATA 0x44 ;RAM location
EQUEQU Used to create symbols that can be used to Used to create symbols that can be used to
represent registers, numbers, and addressesrepresent registers, numbers, and addressesLIMIT EQU 2000LIMIT EQU 2000VALUE EQU LIMIT – 200 + 'A'VALUE EQU LIMIT – 200 + 'A'SERIAL EQU SBUFSERIAL EQU SBUFCOUNT EQU R5COUNT EQU R5MY_VAL EQU 0x44MY_VAL EQU 0x44
Address
Registers, numbers, addresses
Data Transfer Data Transfer InstructionsInstructionsMOV dest, sourceMOV dest, source dest dest source source
6 basic types:6 basic types:MOV a, byteMOV a, byte ;move byte to accumulator ;move byte to accumulator
MOV byte, aMOV byte, a ;move accumulator to byte ;move accumulator to byte
MOV Rn, byteMOV Rn, byte ;move byte to register of ;move byte to register of
;current bank;current bank
MOV direct, byte ;move byte to internal RAMMOV direct, byte ;move byte to internal RAM
MOV @Rn, byteMOV @Rn, byte ;move byte to internal RAM ;move byte to internal RAM ;with address contained ;with address contained
in Rnin Rn
MOV DPTR, data16 ;move 16-bit data into data MOV DPTR, data16 ;move 16-bit data into data
;pointer;pointer
Other Data Transfer Other Data Transfer InstructionsInstructions
Stack instructionsStack instructionsPUSH bytePUSH byte ;increment stack pointer, ;increment stack pointer,
;move byte on stack;move byte on stackPOP bytePOP byte ;move from stack to byte, ;move from stack to byte,
;decrement stack ;decrement stack pointerpointer
Exchange instructionsExchange instructionsXCH a, byteXCH a, byte;exchange accumulator and ;exchange accumulator and
;byte;byteXCHD a, byteXCHD a, byte ;exchange low nibbles ;exchange low nibbles of of ;accumulator and ;accumulator and bytebyte
Addressing Modes Addressing Modes
Immediate Mode Immediate Mode – specify data by its value– specify data by its value
mov a, #0mov a, #0 ;put 0 in the accumulator;put 0 in the accumulator
a = 00000000a = 00000000
mov a, #0x11mov a, #0x11 ; put 11hex in the accumulator; put 11hex in the accumulator
a = 00010001a = 00010001
mov a, #11mov a, #11 ; put 11 decimal in accumulator; put 11 decimal in accumulator
a = 00001011a = 00001011
mov a, #77hmov a, #77h ; put 77 hex in accumulator; put 77 hex in accumulator
a = 01110111a = 01110111
Addressing ModesAddressing ModesDirect ModeDirect Mode – specify data by its 8-bit address – specify data by its 8-bit address
mov a, 0x70 mov a, 0x70 ; copy contents of RAM at 70h to a; copy contents of RAM at 70h to a
mov 0xD0, amov 0xD0, a ; put contents of a into PSW; put contents of a into PSW
Addressing ModesAddressing Modes
Register AddressingRegister Addressing – either source or – either source or destination is one of R0-R7 destination is one of R0-R7
mov R0, amov R0, a
mov a, R0mov a, R0
Addressing ModesAddressing ModesRegister IndirectRegister Indirect – the address of the source or – the address of the source or
destination is specified in registersdestination is specified in registers
Uses registers R0 or R1 for 8-bit address:Uses registers R0 or R1 for 8-bit address:mov 0xD0, #0mov 0xD0, #0 ; use register bank 0; use register bank 0
mov r0, #0x3Cmov r0, #0x3C
mov @r0, #3mov @r0, #3 ; memory at 3C gets #3; memory at 3C gets #3
; M[3C] ; M[3C] 3 3
Uses DPTR register for 16-bit addresses:Uses DPTR register for 16-bit addresses:mov dptr, #0x9000mov dptr, #0x9000 ; dptr ; dptr 9000h 9000h
mov a, @dptrmov a, @dptr ; a ; a M[9000] M[9000]
Note that 9000 is an address in external memoryNote that 9000 is an address in external memory
Exercise: Use Exercise: Use Register Indirect to Register Indirect to access upper RAM access upper RAM blockblock
Addressing ModesAddressing Modes
Register Indexed ModeRegister Indexed Mode – source or – source or destination address is the sum of the destination address is the sum of the base addressbase address and the and the accumulatoraccumulator..
Base address can be Base address can be DPTRDPTR or PC or PCmov dptr, #4000hmov dptr, #4000h
mov a, #5mov a, #5
movc a, @a + dptr ;a movc a, @a + dptr ;a M[4005] M[4005]
Addressing ModesAddressing Modes
Register Indexed ModeRegister Indexed Mode Base address can be DPTR or Base address can be DPTR or PCPC
AddrAddr cseg at 0x1000hcseg at 0x1000h
1000 1000 mov a, #5mov a, #5
10021002 movc a, @a + movc a, @a + PCPC ;a ;a M[1008]M[1008]
10031003 nopnop
PC
A and B RegistersA and B Registers
A and B are “accumulators” for arithmetic A and B are “accumulators” for arithmetic instructionsinstructions
They can be accessed by They can be accessed by direct modedirect mode as as special function registers:special function registers:
B – address 0F0hB – address 0F0h
A – address 0E0h - use “ACC” for direct modeA – address 0E0h - use “ACC” for direct mode
Address ModesAddress ModesStack-oriented data transfer – another form of Stack-oriented data transfer – another form of
register direct addressing, but using SPregister direct addressing, but using SP
mov sp, #0x40mov sp, #0x40 ; Initialize SP; Initialize SPpush 0x55push 0x55 ; SP ; SP SP+1, M[SP] SP+1, M[SP] M[55] M[55]
; M[41] ; M[41] M[55] M[55]pop bpop b ; b ; b M[55] M[55]
Note: can only specify RAM or SFRs (direct mode) to push or Note: can only specify RAM or SFRs (direct mode) to push or pop. Therefore, to push/pop the accumulator, must use acc, pop. Therefore, to push/pop the accumulator, must use acc, not a:not a:
push accpush accpush apush a
StacksStacks
pushpop
stack
stack pointer
Go do the stack exercise…..
Address ModesAddress Modes
Exchange Instructions – two way data Exchange Instructions – two way data transfertransferXCH a, 0x30XCH a, 0x30 ; a ; a M[30] M[30]
XCH a, R0XCH a, R0 ; a ; a R0 R0
XCH a, @R0XCH a, @R0 ; a ; a M[R0] M[R0]
XCHD a, R0XCHD a, R0 ; exchange ; exchange “digit”“digit” R0[7..4] R0[3..0]a[7..4] a[3..0]
Only 4 bits exchanged
Address ModesAddress Modes Bit-Oriented Data TransferBit-Oriented Data Transfer – transfers between individual bits. – transfers between individual bits. SFRs with addresses ending in 0 or 8 are bit-addressable. (80, 88, 90, 98, SFRs with addresses ending in 0 or 8 are bit-addressable. (80, 88, 90, 98,
etc)etc) Carry flag (C) (bit 7 in the PSW) is used as a single-bit accumulatorCarry flag (C) (bit 7 in the PSW) is used as a single-bit accumulator RAM bits in addresses 20-2F are bit addressableRAM bits in addresses 20-2F are bit addressable
Examples of bit transfers of special function register bits:Examples of bit transfers of special function register bits:mov C, P0.0mov C, P0.0 ; C ; C bit 0 of P0 bit 0 of P0
Bit Addressable MemoryBit Addressable Memory20h – 2Fh (16 locations X 8-bits = 128 bits)
7F7F 7878
1A1A
1010
0F0F 0808
0707 0606 0505 0404 0303 0202 0101 0000
27
26
25
24
23
22
21
20
2F
2E
2D
2C
2B
2A
29
28
Bit addressing:mov C, 1Ahormov C, 23h.2
SFRs that are Bit SFRs that are Bit AddressableAddressableSFRs with addresses SFRs with addresses
of multiples of 0 and of multiples of 0 and 8 are bit 8 are bit addressable.addressable.
Notice that all 4 Notice that all 4 parallel I/O ports are parallel I/O ports are bit addressable.bit addressable.
SFRsSFRs
Pink are Pink are implemented in implemented in
enhanced enhanced C8051F020C8051F020
AddressAddress RegisterRegister
0xF80xF8 SPI0CNSPI0CN
0xF00xF0 BB
0xE80xE8 ADC0CNADC0CN
0xE00xE0 ACCACC
0xD80xD8 PCA0CNPCA0CN
0xD00xD0 PSWPSW
0xC80xC8 T2CONT2CON
0xC00xC0 SMB0CNSMB0CN
0xB80xB8 IPIP
0xB00xB0 P3P3
0xA80xA8 IEIE
0xA00xA0 P2P2
0x980x98 SCONSCON
0x900x90 P1P1
0x880x88 TCONTCON
0x800x80 P0P0
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMINGPROGRAMMING
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
Figure 1 Serial versus Parallel Data Transfer
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
serial communication uses single data line making it much serial communication uses single data line making it much cheapercheaper
enables two computers in different cities to communicate enables two computers in different cities to communicate over the telephoneover the telephone
byte of data must be converted to serial bits using a parallel-byte of data must be converted to serial bits using a parallel-in-serial-out register and transmitted over a single data linein-serial-out register and transmitted over a single data line
receiving end there must be a serial-in-parallel-out shift receiving end there must be a serial-in-parallel-out shift registerregister
if transferred on the telephone line, it must be converted to if transferred on the telephone line, it must be converted to audio tones by audio tones by modemmodem
for short distance the signal can be transferred using wirefor short distance the signal can be transferred using wire how PC keyboards transfer data to the motherboard how PC keyboards transfer data to the motherboard
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
2 methods, asynchronous and synchronous2 methods, asynchronous and synchronous synchronous synchronous method transfers a block of data method transfers a block of data
(characters) at a time(characters) at a time asynchronous asynchronous method transfers a single byte method transfers a single byte
at a timeat a time Uses special IC chips called UART (universal Uses special IC chips called UART (universal
asynchronous receiver-transmitter) and asynchronous receiver-transmitter) and USART (universal synchronous asynchronous USART (universal synchronous asynchronous receiver-transmitter)receiver-transmitter)
8051 chip has a built-in UART 8051 chip has a built-in UART
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
Figure 2 Simplex, Half-, and Full-Duplex Transfers
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
Half- and full-duplex transmissionHalf- and full-duplex transmission if the data can be transmitted and received, it is a if the data can be transmitted and received, it is a
duplex duplex transmissiontransmission simplex simplex transmissions the computer only sends datatransmissions the computer only sends data duplex transmissions can be half or full duplexduplex transmissions can be half or full duplex depends on whether or not the data transfer can be depends on whether or not the data transfer can be
simultaneoussimultaneous If one way at a time, it is If one way at a time, it is half duplexhalf duplex If can go both ways at the same time, it is full duplexIf can go both ways at the same time, it is full duplex full duplex requires two wire conductors for the data full duplex requires two wire conductors for the data
lines (in addition to the signal ground)lines (in addition to the signal ground)
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
Asynchronous serial communication Asynchronous serial communication and data framingand data framing data coming in 0s and 1sdata coming in 0s and 1s to make sense of the data sender and to make sense of the data sender and
receiver agree on a set of rulesreceiver agree on a set of rules ProtocolProtocol
how the data is packedhow the data is packed how many bits/characterhow many bits/character when the data begins and endswhen the data begins and ends
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
Start and stop bitsStart and stop bits asynchronous method, each character is asynchronous method, each character is
placed between start and stop bitsplaced between start and stop bits called called framingframing start bit is always one bitstart bit is always one bit stop bit can be one or two bitsstop bit can be one or two bits start bit is always a 0 (low)start bit is always a 0 (low) stop bit(s) is 1 (high)stop bit(s) is 1 (high) LSB is sent out firstLSB is sent out first
SECTION 10.1: BASICS OF SECTION 10.1: BASICS OF SERIAL COMMUNICATIONSERIAL COMMUNICATION
Figure 3 Framing ASCII “A” (41H)
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
in modern PCs one stop bit is standardin modern PCs one stop bit is standard when transferring a text file of ASCII when transferring a text file of ASCII
characters using 1 stop bit there is total characters using 1 stop bit there is total of 10 bits for each characterof 10 bits for each character
8 bits for the ASCII code (1 parity bit), 1 8 bits for the ASCII code (1 parity bit), 1 bit each for the start and stop bitsbit each for the start and stop bits
for each 8-bit character there are an extra for each 8-bit character there are an extra 2 bits, which gives 20% overhead2 bits, which gives 20% overhead
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
Data transfer rateData transfer rate rate of data transfer rate of data transfer bps bps (bits per second)(bits per second) widely used terminology for bps is widely used terminology for bps is baud baud
raterate baud and bps rates are not necessarily baud and bps rates are not necessarily
equalequal baud rate is defined as the number of baud rate is defined as the number of
signal changes per secondsignal changes per second
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
RS232 standardsRS232 standards most widely used serial I/O interfacing standardmost widely used serial I/O interfacing standard input and output voltage levels are not TTL compatibleinput and output voltage levels are not TTL compatible 1 bit is represented by -3 to -25 V1 bit is represented by -3 to -25 V 0 bit is +3 to +25 V0 bit is +3 to +25 V -3 to +3 is undefined-3 to +3 is undefined to connect RS232 to a microcontroller system must use to connect RS232 to a microcontroller system must use
voltage converters such as MAX232 to convert the TTL voltage converters such as MAX232 to convert the TTL logic levels to the RS232 voltage levels, and vice versalogic levels to the RS232 voltage levels, and vice versa
MAX232 IC chips are commonly referred to as line MAX232 IC chips are commonly referred to as line driversdrivers
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
Table 2 IBM PC DB-9 Signals
Figure 5 DB-9 9-Pin Connector
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
Data communication classificationData communication classification DTE (data terminal equipment) DTE (data terminal equipment) DCE (data communication equipment)DCE (data communication equipment) DTE - terminals and computers that send and DTE - terminals and computers that send and
receive datareceive data DCE - communication equipment responsible for DCE - communication equipment responsible for
transferring the datatransferring the data simplest connection between a PC and simplest connection between a PC and
microcontroller requires a minimum of three microcontroller requires a minimum of three pins, TxD, RxD, and groundpins, TxD, RxD, and ground
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
Figure 6 Null Modem Connection
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
Examining RS232 hand shaking Examining RS232 hand shaking signalssignals many of the pins of the RS-232 connector many of the pins of the RS-232 connector
are used for handshaking signalsare used for handshaking signals they are not supported by the 8051 UART they are not supported by the 8051 UART
chipchip
BASICS OF SERIAL BASICS OF SERIAL COMMUNICATIONCOMMUNICATION
PC/compatible COM portsPC/compatible COM ports PC/compatible computers (Pentium) PC/compatible computers (Pentium)
microprocessors normally have two COM microprocessors normally have two COM portsports
both ports have RS232-type connectorsboth ports have RS232-type connectors COM ports are designated as COM 1 and COM ports are designated as COM 1 and
COM 2COM 2 can connect the 8051 serial port to the can connect the 8051 serial port to the
COM 2 portCOM 2 port
8051 CONNECTION TO 8051 CONNECTION TO RS232RS232
RxD and TxD pins in the 8051RxD and TxD pins in the 8051 8051 has two pins used for transferring and 8051 has two pins used for transferring and
receiving data seriallyreceiving data serially TxD and RxD are part of the port 3 group TxD and RxD are part of the port 3 group pin 11 (P3.1) is assigned to TxDpin 11 (P3.1) is assigned to TxD pin 10 (P3.0) is designated as RxDpin 10 (P3.0) is designated as RxD these pins are TTL compatiblethese pins are TTL compatible require a line driver to make them RS232 require a line driver to make them RS232
compatiblecompatible driver is the MAX232 chipdriver is the MAX232 chip
8051 CONNECTION TO 8051 CONNECTION TO RS232RS232
MAX232MAX232 converts from RS232 voltage levels to TTL converts from RS232 voltage levels to TTL
voltage levelsvoltage levels uses a +5 V power sourceuses a +5 V power source MAX232 has two sets of line drivers for MAX232 has two sets of line drivers for
transferring and receiving datatransferring and receiving data line drivers used for TxD are called T1 and T2line drivers used for TxD are called T1 and T2 line drivers for RxD are designated as R1 and R2line drivers for RxD are designated as R1 and R2 T1 and R1 are used together for TxD and RxD of T1 and R1 are used together for TxD and RxD of
the 8051the 8051 second set is left unusedsecond set is left unused
SECTION 10.2: 8051 SECTION 10.2: 8051 CONNECTION TO RS232CONNECTION TO RS232
Figure 7 (a) Inside MAX232(b) its Connection to the 8051 (Null Modem)
SECTION 10.2: 8051 SECTION 10.2: 8051 CONNECTION TO RS232CONNECTION TO RS232
MAX233MAX233 MAX233 performs the same job as the MAX233 performs the same job as the
MAX232MAX232 eliminates the need for capacitorseliminates the need for capacitors much more expensive than the MAX232much more expensive than the MAX232
8051 CONNECTION TO 8051 CONNECTION TO RS232RS232
Figure 8 (a) Inside MAX233(b) Its Connection to the 8051 (Null Modem)
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
Baud rate in the 8051Baud rate in the 8051 serial communications of the 8051 with serial communications of the 8051 with
the COM port of the PCthe COM port of the PC must make sure that the baud rate of the must make sure that the baud rate of the
8051 system matches the baud rate of the 8051 system matches the baud rate of the PC's COM portPC's COM port
can use Windows HyperTerminal can use Windows HyperTerminal programprogram
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
Table 3 PC Baud Rates
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
Baud rate in the 8051Baud rate in the 8051 baud rate in the 8051 is programmablebaud rate in the 8051 is programmable done with the help of Timer 1done with the help of Timer 1 relationship between the crystal frequency and the baud rate in relationship between the crystal frequency and the baud rate in
the 8051the 8051 8051 divides the crystal frequency by 12 to get the machine 8051 divides the crystal frequency by 12 to get the machine
cycle frequencycycle frequency XTAL = 11.0592 MHz, the machine cycle frequency is 921.6 kHzXTAL = 11.0592 MHz, the machine cycle frequency is 921.6 kHz 8051's UART divides the machine cycle frequency of 921.6 kHz 8051's UART divides the machine cycle frequency of 921.6 kHz
by 32 once more before it is used by Timer 1 to set the baud rateby 32 once more before it is used by Timer 1 to set the baud rate 921.6 kHz divided by 32 gives 28,800 Hz921.6 kHz divided by 32 gives 28,800 Hz Timer 1 must be programmed in mode 2, that is 8-bit, auto-reloadTimer 1 must be programmed in mode 2, that is 8-bit, auto-reload
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
Table 4 Timer 1 TH1 Register Values for Various Baud Rates
Example 1Example 1With XTAL = 11.0592 MHz, find the TH1 value With XTAL = 11.0592 MHz, find the TH1 value needed to have the following baud rates.needed to have the following baud rates.
(a) 9600(a) 9600 (b) 2400(b) 2400 (c) 1200(c) 1200 machine cycle frequencymachine cycle frequency
= 11.0592 MHz / 12 = 921.6 kHz= 11.0592 MHz / 12 = 921.6 kHz Timer 1 frequency provided by 8051 Timer 1 frequency provided by 8051
UARTUART= 921.6 kHz / 32 = 28,800 Hz = 921.6 kHz / 32 = 28,800 Hz
(a) 28,800 / 3 = 9600(a) 28,800 / 3 = 9600 where -3where -3 = FD (hex)= FD (hex)(b) 28,800 / 12 = 2400(b) 28,800 / 12 = 2400 where -12where -12 = F4 (hex)= F4 (hex)
(c) 28,800 / 24 = 1200(c) 28,800 / 24 = 1200 where -24where -24 = E8 (hex= E8 (hex))
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
11.0592 MHz11.0592 MHzXTAL XTAL
oscillatoroscillator
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
SBUF (serial buffer) registerSBUF (serial buffer) register a byte of data to be transferred via the TxD line must a byte of data to be transferred via the TxD line must
be placed in the SBUF registerbe placed in the SBUF register SBUF holds the byte of data when it is received by the SBUF holds the byte of data when it is received by the
RxD lineRxD line can be accessed like any other registercan be accessed like any other register
MOV SBUF,#'D'MOV SBUF,#'D' ;load SBUF=44H, ASCII for 'D‘;load SBUF=44H, ASCII for 'D‘MOV SBUF,AMOV SBUF,A ;copy accumulator into SBUF;copy accumulator into SBUFMOV A,SBUFMOV A,SBUF ;copy SBUF into accumulator;copy SBUF into accumulator
when a byte is written, it is framed with the start and when a byte is written, it is framed with the start and stop bits and transferred serially via the TxD pinstop bits and transferred serially via the TxD pin
when the bits are received serially via RxD, it is when the bits are received serially via RxD, it is deframe by eliminating the stop and start bits, making deframe by eliminating the stop and start bits, making a byte out of the data received, and then placing it in a byte out of the data received, and then placing it in the SBUFthe SBUF
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
SCON (serial control) registerSCON (serial control) register to program the start bit, stop bit, and data to program the start bit, stop bit, and data
bitsbits
Figure 9 SCON Serial Port Control Register (Bit-Addressable)
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
SM0 and SM1 determine the modeSM0 and SM1 determine the mode only mode 1 is importantonly mode 1 is important when mode 1 is chosen, the data framing is 8 when mode 1 is chosen, the data framing is 8
bits, 1 stop bit, and 1 start bitbits, 1 stop bit, and 1 start bit compatible with the COM port of PCscompatible with the COM port of PCs mode 1 allows the baud rate to be variable and mode 1 allows the baud rate to be variable and
is set by Timer 1 of the 8051is set by Timer 1 of the 8051 for each character a total of 10 bits are for each character a total of 10 bits are
transferred, where the first bit is the start bit, transferred, where the first bit is the start bit, followed by 8 bits of data, and finally 1 stop bit.followed by 8 bits of data, and finally 1 stop bit.
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
REN (receive enable) REN (receive enable) REN=1, allows 8051 to receive data on REN=1, allows 8051 to receive data on
the RxDthe RxD if 8051 is to both transfer and receive if 8051 is to both transfer and receive
data, REN must be set to 1data, REN must be set to 1 REN=0, the receiver is disabledREN=0, the receiver is disabled SETB SCON.4 and CLR SCON.4, SETB SCON.4 and CLR SCON.4,
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
TI (transmit interrupt)TI (transmit interrupt) when 8051 finishes the transfer of the 8-bit when 8051 finishes the transfer of the 8-bit
character, it raises the TI flag to indicate that it is character, it raises the TI flag to indicate that it is ready to transfer another byteready to transfer another byte
RI (receive interrupt)RI (receive interrupt) when the 8051 receives data serially via RxD, it when the 8051 receives data serially via RxD, it
places the byte in the SBUF registerplaces the byte in the SBUF register then raises the RI flag bit to indicate that a byte has then raises the RI flag bit to indicate that a byte has
been received and should be picked up before it is been received and should be picked up before it is lostlost
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
Program to transfer data seriallyProgram to transfer data serially1.1. TMOD register is loaded with the value 20HTMOD register is loaded with the value 20H2.2. TH1 is loaded with value to set the baud rateTH1 is loaded with value to set the baud rate3.3. SCON register is loaded with the value 50HSCON register is loaded with the value 50H4.4. TR1 is set to 1 to start Timer1TR1 is set to 1 to start Timer15.5. TI is cleared by the "CLR TI" instructionTI is cleared by the "CLR TI" instruction6.6. transmit character byte is written into the SBUF transmit character byte is written into the SBUF
registerregister7.7. TI flag bit is monitored to see if the character has TI flag bit is monitored to see if the character has
been transferred completelybeen transferred completely8.8. to transfer the next character, go to Step 5.to transfer the next character, go to Step 5.
Example 2Example 2Write a program to transfer letter "A" Write a program to transfer letter "A" serially at 4800 baud, continuously.serially at 4800 baud, continuously.
Example 3Example 3Write a program to transfer the message Write a program to transfer the message "YES" serially at 9600 baud, 8-bit data, 1 "YES" serially at 9600 baud, 8-bit data, 1 stop bit. Do this continuously. stop bit. Do this continuously.
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
Importance of the TI flagImportance of the TI flag check the TI flag bit, we know whether check the TI flag bit, we know whether
can transfer another bytecan transfer another byte TI flag bit is raised by the 8051TI flag bit is raised by the 8051 TI flag cleared by the programmerTI flag cleared by the programmer writing a byte into SBUF before the TI flag writing a byte into SBUF before the TI flag
bit is raised, may lead to loss of a portion bit is raised, may lead to loss of a portion of the byte being transferredof the byte being transferred
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
Program to receive data seriallyProgram to receive data serially1.1. TMOD register is loaded with the value 20HTMOD register is loaded with the value 20H2.2. TH1 is loaded with value set the baud rateTH1 is loaded with value set the baud rate3.3. SCON register is loaded with the value 50HSCON register is loaded with the value 50H4.4. TR1 is set to 1 to start Timer 1TR1 is set to 1 to start Timer 15.5. RI is cleared with the "CLR RI" instructionRI is cleared with the "CLR RI" instruction6.6. RI flag bit is monitored to see if an entire RI flag bit is monitored to see if an entire
character has been received yetcharacter has been received yet7.7. RI=1 SBUF has the byte, its contents are moved RI=1 SBUF has the byte, its contents are moved
into a safe placeinto a safe place8.8. to receive the next character, go to Step 5to receive the next character, go to Step 5
Example 4Example 4Program the 8051 to receive bytes of data Program the 8051 to receive bytes of data serially, and put them in P1. Set the baud serially, and put them in P1. Set the baud rate at 4800, 8-bit data, and 1 stop bit.rate at 4800, 8-bit data, and 1 stop bit.
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
Importance of the RI flag bitImportance of the RI flag bit1.1. it receives the start bit, next bit is the first bit of it receives the start bit, next bit is the first bit of
the characterthe character
2.2. when the last bit is received, a byte is formed when the last bit is received, a byte is formed and placed in SBUFand placed in SBUF
3.3. when stop bit is received, makes RI = 1when stop bit is received, makes RI = 1
4.4. when RI=1, received byte is in the SBUF when RI=1, received byte is in the SBUF register, copy SBUF contents to a safe placeregister, copy SBUF contents to a safe place
5.5. after the SBUF contents are copied the RI flag after the SBUF contents are copied the RI flag bit must be cleared to 0bit must be cleared to 0
8051 SERIAL PORT 8051 SERIAL PORT PROGRAMMING IN PROGRAMMING IN ASSEMBLYASSEMBLY
Doubling the baud rate in the 8051Doubling the baud rate in the 8051 two ways to increase the baud ratetwo ways to increase the baud rate
1.1. Use a higher-frequency crystalUse a higher-frequency crystal
2.2. Change a bit in the PCON registerChange a bit in the PCON register
Table 5 Baud Rate Comparison for SMOD = 0 and SMOD = 1