Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lecture Programming Microcontroller

Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

The 8051

Assembly Language
8051 Instruction Set

The 8051 instruction set can be divided into 5 subgroups: -

• Data Transfer
– MOV instructions used to transfer data internal and external to the 8051
• Arithmetic
– Add, subtract, multiply, divide
• Logical
– AND, OR, XOR, NOT and rotate operations
• Boolean variable manipulation
– Operations on bit variables
• Program Branching
– Conditional and unconditional jump instructions
Some Useful Directives
• END
– Last line of code. Assembler will not compile after this line
• ORG
– Origin directive. Sets the location counter address for the following
instructions
– ORG 0000H
• EQU
– Equate directive. Used to equate a name with an address or a data value.
Useful for constant assignments.
– COUNT EQU 25
– MOV R3, #COUNT
• BIT
– Used to assign a symbol name to a bit in bit-addressable data memory

– DB (Define Byte)
– Used to define 8bit data
– DB 28, DB 45H, DB 01011101B, DB 23H, 45H, …
Data transfer Instructions

mov A, #0 ;put 0 in the accumulator


;A = 00000000
mov R4, #11h ;put 11hex in the R4 register
;R4 = 00010001
mov B, #11 ;put 11 decimal in b register
;B = 00001011

mov DPTR,#7521h ;put 7521 hex in DPTR


;DPTR = 0111010100100001
Data transfer Instructions
MOV R0,A
MOV A,R7
ADD A,R4
ADD A,R7
MOV DPTR,#25F5H
MOV R5,DPL
MOV R,DPH

Note that MOV R4,R7 is incorrect


Data transfer Instructions

specify data by its 8-bit address


Usually for 30h-7Fh of RAM
Mov a, 70h ; copy contents of RAM at
70h to a
Mov R0,40h ; copy contents of RAM at
70h to R0
Bit-Oriented Data Transfer
 transfers between individual bits.
 Carry flag (C) (bit 7 in the PSW) is used as a single-
bit accumulator
 RAM bits in addresses 20-2F are bit addressable

mov C, 67h
mov C, 2ch.7
8051 Arithmetic Operations
• All arithmetic operations are carried out in the ALU
• The 8051 has 4 arithmetic flags that are stored in the PSW register

1. C Carry Flag
Set if there is a carry out after addition or a borrow after subtraction. Used for unsigned
arithmetic.

2. AC Auxiliary Carry Flag


Set if there is a carry out of bit 3 during addition or a borrow during subtraction. Used for
BCD arithmetic.

3. OV Overflow Flag
Set if there is a carry from bit 6 XOR bit 7 Used for signed arithmetic

4. P Parity Flag
Contains the parity of the accumulator. 1 if odd, 0 if even. Useful for some serial port
operations.
Increment/Decrement Instructions
• INC Source
– Adds 1 to the source

• DEC Source
– Subtract 1 from the source

• Source may be a register or a direct or indirect address


– INC A
– DEC R1
– INC 30H
– DEC @R0

• No flags are affected by the INC and DEC instructions


Multiply/Divide Instructions

• MUL AB
– Note no comma between source and destination
– Multiplies the A register by the B register. The low order byte of the result is placed
in A, the high order byte in B.
– The OV flag is set if the result exceeds 255

• DIV AB
– Divides A register by B register.
– The integer part of the quotient is placed in A, the integer part of the remainder is
placed in B.
– OV flag is set if a divide by 0 is attempted
Addition
ADD A, SOURCE ;A = A + Source

ADDC A, SOURCE ;A = A + Source + C

• The accumulator is always used to store the result


• All addressing modes may be used.

• Affect on flags
– Carry bit C is set if there is a carry out of bit 7, cleared otherwise.
• Used for unsigned addition
– AC flag set if there is a carry from bit 3, cleared otherwise
• Used for BCD addition
– OV flag is set if C7 XOR C6, cleared otherwise
• Used for signed addition
Unsigned Addition
• The carry bit C should always be tested after an addition to see if the result has
exceeded 255 (FFH).
– JC Label ;jump if carry bit is set
– JNC Label ;jump if carry bit is clear

Examples: -

25 00011001
47 00101111
72 01001000 No carry (result <=255)

65 01000001
208 11010000
273 1 00010001 Carry (result > 255)
Unsigned Addition
• Write a program to add the contents of internal data memory locations 30H and 31H If
a carry occurs, set the pin P1.0

ERROR BIT P1.0


MAIN: CLR ERROR
LOOP: MOV A, 30H ADD
A, 31H
JNC MAIN ;no carry
SETB ERROR ;carry, set error
pin
JMP LOOP
END
Signed Addition
• For signed arithmetic bit 7 of the number is used as a sign bit.
– 1 for a negative number and 0 for a positive number
– Number range is restricted to –128 to +127

• The OV flag should always be tested after adding 2 signed numbers


– The OV flag will only change when adding numbers of the same sign yields a
result outside of the range –128 to +127

Examples: -
+25 00011001
-45 11010011
-20 11101100 ;OV = 0, take no action

+120 01111000
+48 00110000
+168 10101000 ;OV = 1, result is –88? Need to adjust result
Signed Addition
+120 01111000
+48 00110000
+168 10101000 ;OV = 1, result is –88? Need to adjust result

• How do we adjust the result to get the correct value (+168)?


– Remember that the result range is –128 to +127
– If there is an overflow this range has been exceeded
– Invert bit 7 to get the correct polarity for the result
– The result then needs to be adjusted by +/-128 depending on whether we are
adding positive or negative numbers

• For the above example, inverting the result bit 7 yields 00101000 (+40)
– Because of the overflow the real result is 40 +128 = 168.
Adding 2-Byte Numbers
• Write a program to add 2 integers.
– Integer 1 is stored at addresses 30H and 31H (low byte at address 30H)
– Integer 2 is stored at addresses 32H and 33H (low byte at address 32H)
– The result should be stored at addresses 34H to 36H (low byte at address 34H)

• Hint
– Use the ADDC instruction instead of ADD
BCD Addition
• The 8051 performs addition in pure binary – this may lead to errors when performing
BCD addition

Example

49 BCD 01001001 BCD


38 BCD 00111000 BCD
87 BCD 10000001 (81BCD)

• The result must be adjusted to yield the correct BCD result


– DA A (decimal adjust instruction)
– The carry flag is set if the adjusted number exceeds 99 BCD

MOV A, #9
ADD A, #11 ;A = 1AH (expecting 20H if these are BCD numbers)
DA A ;A = 20H
Subtraction
• SUBB A, SOURCE
– Subtracts source and carry flags from A
– Result placed in A

• For unsigned subtraction the carry flag C is set if there is a borrow needed for bit 7

• For signed subtraction the OV flag is set if the subtraction of a negative number from a
positive number yields a negative result or if the subtraction of a positive number from
a negative number yields a positive result.
Arithmetic Instructions

Mnemonic Description
ADD A, byte add A to byte, put result in A
ADDC A, byte add with carry
SUBB A, byte subtract with borrow
INC A increment A
INC byte increment byte in memory
INC DPTR increment data pointer
DEC A decrement accumulator
DEC byte decrement byte
MUL AB multiply accumulator by b register
DIV AB divide accumulator by b register
DA A decimal adjust the accumulator
8051 Logical Operations
• All 4 addressing modes may be used for the 8051 logical instructions

• AND
– ANL A,SOURCE
– May be used to selectively clear bits in the destination operand
– e.g. ANL A, #11111100B ;will clear lower 2 bits of A register

• OR
– ORL A, SOURCE
– May be used to selectively set bits in the destination operand
– ORL A, #00000001B ;will set bit 0 of A register

• XOR
– XRL A, SOURCE
– May be used to selectively complement bits in the destination operand
– XRL P1, #00001111B ;will complement lower 4 bits of port 1
Bitwise Logic

Examples:
ANL  AND 00001111
ORL  OR ANL 10101100
00001100
XRL  XOR
CPL  Complement 00001111
ORL 10101100
10101111

00001111
XRL 10101100
10100011

CPL 10101100
01010011
8051 Logical Operations

• Complement
– CPL A
– Complements each bit of the A register

• Clear
– CLR A
– Clears each bit of the A register
Other Logic Instructions

CLR - clear
RL – rotate left
RLC – rotate left through Carry
RR – rotate right
RRC – rotate right through Carry
SWAP – swap accumulator nibbles
Rotate Operations
• All rotate operations are carried out on the accumulator
• RL A
– Rotate accumulator left, MSB becomes LSB
7 6 5 4 3 2 1 0

• RLC A
– Rotate accumulator left, MSB becomes carry, carry becomes LSB
C 7 6 5 4 3 2 1 0

• Similar operations for rotate right: - RR A, RRC A


Bit Level Logical Operations
• These instructions allow a single bit to be altered without affecting the entire byte
– Can be used to set/clear a bit in bit-addressable memory
– Can be used to set/clear an I/O pin
• SETB BIT ;sets bit high
• CLR BIT ;clears bit low

• Example
SETB P1.0 ;P1.0 = ‘1’
CLR P1.0 ;P1.0 = ‘0’

or

LED BIT P1.0 ;use BIT directive to name pin


SETB LED
Bit-level Boolean Operations
8051 Addressing modes

• The 8051 uses 4 addressing modes:


-
– Immediate Addressing
– Register Addressing
– Direct Addressing
– Register Indirect Addressing
Immediate Addressing
• In immediate addressing the data source is always a number and is specified by a ‘#’.
– The number specified is copied into the destination

MOV A, #10 ;moves number 10 into Accumulator


MOV R0, #0AH ;moves number 10 into R0

• Assembler Number Representation


– Default numbering system is decimal
– Hexadecimal numbers must be followed by the letter H and must begin with a
number i.e. the number FA Hex is written as 0FAH.
– Binary numbers must be followed by the letter B.

– The following instructions have the same effect


MOV R0, #255 MOV R0, #0FFH
MOV R0, #11111111B
Register Addressing

• Internal registers A, R0 to R7 and DPTR may be used as the source or the destination.

MOV A, R0 ;copies contents of R0 to A

• Note: - Data may not be copied from Rn to Rn


– MOV R0, R1 will generate an assembler error
• The source remains unchanged.
Direct Addressing
• Direct Addressing is used in instructions that affect internal data memory locations or
the SFR’s.
– The internal data memory address range is 0 to 127 (0 to 7FH)

MOV A, 20H ;copies contents of address 20H into the Accumulator MOV 30H,

40H ;copies contents of address 40H to address 30H MOV P1, A ;move the

contents of the Accumulator to Port 1


Indirect Addressing
• The most powerful addressing mode.
• A register is used to store the address of the destination or source of data
– Similar to the use of pointers in high level languages
– The @ symbol is used before the register to specify indirect addressing
– SFRs may not be indirectly addressed
– Internal data memory may be directly or indirectly addressed

MOV R0, #20H ;Load R0 with the number 20H


MOV @R0, #55H ;Move 55H to the address contained in R0 (20H)
;R0 acts as a pointer to address 20H
MOV A, @R0 ;Copy the contents of address 20H to the Accumulator

• Only registers R0 and R1 may be used for moving data to/from internal data memory
when using indirect addressing
• Registers R0, R1 and DPTR may be used when indirectly addressing external memory
(more later)
Addressing Modes Exercise

• What are the contents of registers A, R0, R7 and memory locations 30H and 31H after
the following code runs: -
MOV A, #5 MOV R7, #40H MOV R0, #30H MOV 31H, #14H MOV @RO, A INC R0
MOV R7, @R0

• How long does the code take to execute if the 8051 is operating off a 12MHz crystal?
Unconditional Jumps

SJMP <rel addr> ; Short jump,


relative address is 8-bit 2’s complement
number, so jump can be up to 127 locations
forward, or 128 locations back.
LJMP <address 16> ; Long jump

AJMP <address 11> ; Absolute jump to


anywhere within 2K block of program memory
JMP @A + DPTR ; Long
indexed jump
Unconditional Jumps
The 8051 has 3 unconditional jump instructions with a different range: -
•SJMP (Short Jump)
– Allows a jump of –128 to +127 bytes relative to the current PC value( first byte of
the following instruction
– Instruction is 2 bytes long

•AJMP (Absolute Jump)


– Allows a jump with the same 2KByte page that the PC is currently located in(from
the next instruction followed by AJMP instruction.
– Instruction is 2 bytes long

•LJMP (Long Jump)


– Allows a jump anywhere within the 64KByte program memory range of the 8051

•If unsure which of the 3 instructions to use, simply use the JMP instruction and let the
assembler decide which instruction to use.
Conditional Jump

 These instructions cause a jump to occur only if a


condition is true. Otherwise, program execution
continues with the next instruction.

loop: mov a, P1
jz loop ; if a=0, goto loop,
; else goto next instruction
mov b, a

 There is no zero flag (z)


 Content of A checked for zero on time
Conditional jumps
Mnemonic Description
JZ <rel addr> Jump if a = 0
JNZ <rel addr> Jump if a != 0
JC <rel addr> Jump if C = 1
JNC <rel addr> Jump if C != 1
JB <bit>, <rel addr> Jump if bit = 1
JNB <bit>,<rel addr> Jump if bit != 1
JBC <bir>, <rel addr> Jump if bit =1, &clear
bit
CJNE A, direct, <rel addr> Compare A and memory,
jump if not equal
More Conditional Jumps

Mnemonic Description
CJNE A, #data <rel addr> Compare A and data, jump
if not equal
CJNE Rn, #data <rel addr> Compare Rn and data,
jump if not equal
CJNE @Rn, #data <rel addr> Compare Rn and memory,
jump if not equal
DJNZ Rn, <rel addr> Decrement Rn and then
jump if not zero

DJNZ direct, <rel addr> Decrement memory and


then jump if not zero
DJNZ Instruction
• Decrement and Jump if Not Zero
– DJNZ Rn, label
– DJNZ direct address, label

• DJNZ is used to execute a block of code N times


– Similar to a for or while loop in C
– Very useful for generating delays

MOV R0, #10 ;R0 = loop counter


LOOP: DJNZ R0, LOOP ;DJNZ instruction executed 10
times
MOV A, R1
Interrupt Priority (IP) SFR
Interrupt Enable (IE) SFR
Using Stack Pointer

 MOV 55H, #23H


MOV SP, #55H
POP DPH Finally, DPH will contain 23H, SP
will have 54H.

MOV DPL,#44H
MOV SP,#54H
PUSH DPL Finally the location 55H in Stack
memory will be loaded with contents of DPL, i.e. 44H.
Using Interrupts

 Initialize the external interrupt 0


MOV IE, #10000100B

Assigning Interrupt priorities


MOV IE, #10001100B : Enable EX1 and ET1
SETB PT1

MOV IE, #10001100B : Enable EX1 and ET1


SETB PT1
SETB PX1
Using Timer

 A machine cycle of 8051 consists of 12 oscillator


periods or the counting rate is 1/12 of the oscillator
frequency. At 12 MHz , the clocking period will be
equal to 1 microsecond.
 MOV TMOD, #10000000B : Timer 1 in Mode 0,
Timer 0 in Mode 0
SETB TR1 : Start timer 1
SETB TR0 : Start timer 0
CLR TR1 : Stop timer 1
SJMP $ : Infinite loop (jump here)
Using Timer

 Program to generate 2 KHz square wave on pin P1.0


 MOV SP, #54H

MOV TMOD , 0000 0010B: Timer 0 in Mode 2(Auto reload mode)


MOV TH0, #06H; Preload value for 2 KHz
MOV TL0, #06H; Starting value in Timer Register TL0
SETB TR0; Start timer 0
LOOP:JB TF0, COMPLEMENT
SJMP LOOP
COMPLEMENT: CPL P1.0; Toggle bit P1.0
SJMP LOOP
Using Timer

 Program to generate stair case ramp


 MOV A, #00H
 REPEAT: MOV P1, A
 INC A
 LCALL DLY
 SJMP REPEAT

 DLY: MOV R), #COUNT


 LOOP: DJNZ R0, LOOP
 RET
Machine Cycle

 In original 8051, one machine cycle lasts for 12


oscillator period. If clock frequency is 12 MHz then
1 t-state=1 Microsecond.
DJNZ for Generating Delays
MOV R0, #10 ;R0 = loop counter
LOOP: DJNZ R0, LOOP ;DJNZ instruction executed 10
times
MOV A, R1
• The DJNZ instruction takes 2 machine cycles to execute (24 clocks)
• If the 8051 is operating from a 12MHz crystal, the loop execution time is (10 *
24)/12000000 = 20usec

• The maximum delay for a single loop occurs when the loop counter is initialised
to 0
– This will cause 256 loop iterations
– Delay = (256 * 24)/12000000 = 512usec

• How do we generate delays longer than 512usec?


DJNZ for Generating Delays
• Longer delays may be generated by using nested DJNZ instructions

MOV R0, #0 ;12 clocks


MOV R1, #200 ;12 clocks
LOOP: DJNZ R0, LOOP ;256 * 24 clocks
DJNZ R1, LOOP ;executes inner loop + DJNZ 200
times
• Execution time is (12 + 12 + 200((256*24) + 24))/12000000 = 0.102802 sec

• Rewrite the code to generate a delay of 0.1usec accurate to 10usec


DJNZ Exercise
MOV R0, #0
MOV R1, #0
MOV R2, #10
LOOP: DJNZ R0, LOOP
DJNZ R1, LOOP
DJNZ R2, LOOP

1. How long does the above code take to execute if the 8051 is operating off a 12MHz
crystal?
2. Repeat part 1 for a 16MHz crystal
3. Rewrite the code to generate a delay of 1 second accurate to 10usec (assume a
12MHz crystal)
Subroutines
• A subroutine is a block of code that can be used many times in the execution of a larger
program (similar to functions in higher level languages)
• Subroutines allow the program to branch to a section of code and to remember where it
branched from.
• When the subroutine is complete program execution will continue from the line of code
following the subroutine call.

• Subroutines have the following advantages: -


– Code savings
• The same subroutine may be called over and over again
– Program structuring
• A large program may be divided into a number of small subroutines
• This makes the program easer to maintain and debug
Call and Return

Call is similar to a jump, but


Call pushes PC on stack before branching

acall <address ll> ; stack  PC


; PC  address 11 bit

lcall <address 16> ; stack  PC


; PC  address 16 bit
Return

Return is also similar to a jump, but


Return instruction pops PC from stack to get
address to jump to

ret ; PC  stack
Look-Up Tables
• A look-up table is a table of constants stored in program memory
– Look-up tables can be used to speed up arithmetic operations
– The look-up table may be accessed using the DPTR or PC as a pointer to the start of
the table. The A register is used as an index to the table.

MOVC A, @A+DPTR MOVC A, @A+PC

– The look-up table is defined using the DB directive


ORG 200H DB 1,2,4,9
– This code will create a look-up table at address 200H. The value 1 will be stored at
address 200H, 2 at address 201H etc
– Ensure that the look-up table does not overlap with the address space used by code.
Look-up Table Example
• Write a program to read an 8-bit temperature in Celsius from Port 1 and to output the
Farenheight temperature equivalent onto Port 2
– F = ((C * 9)/5) + 32

• This temperature conversion could be coded in 2 ways: -


– Use arithmetic operations to work out the formula
• This would involve a multiply and a divide operation which are the 2
instructions with the longest execution time
• The code would also have to deal with the 2-byte result of the multiply

– Use a look-up table that stores the Farenheight equivalent of all possible Celsius
readings
• This would require more program memory – 1 byte for each temperature
• The code is much simpler to implement
Temperature Conversion Program
TABLE EQU 100H ORG 0
MAIN: MOV DPTR, #TABLE LOOP: MOV A, P1
MOVC A, @A+DPTR MOV P2, A
JMP LOOP

;conversion look-up table for 0 to 40 degrees Celsius ORG TABLE


DB 32,34,36,37,39,41,43,45,46,48,50,52,54,55,57,59,61,63,64,66
DB 70,72,72,75,77,79,81,82,84,86,88,90,91,93,95,97,99,100,102,104
END

;What happens if a value outside of the range 0 to 40 is read from Port


1?
;How do you deal with this scenario in code?
Some Examples of ALP

 Addition of two numbers

ORG 0000H
SJMP MAIN
MAIN: MOV 40H, #88H
MOV A,#0A9H
ADD A,40H
END
Some Examples of ALP

 Bitwise AND operation

ORG 0000H
SJMP MAIN
MAIN: MOV A, #0FFH/ MOV A,#0XFF
SETB C/CLR C
ANL C,ACC.0
END
Some Examples of ALP

 BCD Operation

ORG 0000H
SJMP MAIN
MAIN: MOV A, #28H
ADD A, #12H
DA A
END
Some Examples of ALP

 Multiplication of two numbers : Lower Byte-A


Upper Byte-B

ORG 0000H
SJMP MAIN
MAIN: MOV A, #07H
MOV B, #08H
MUL AB
END
Some Examples of ALP

 Division of two numbers: Quotient- A, Remainder-B

ORG 0000H
SJMP MAIN
MAIN: MOV A, #38H
MOV B, #08H
DIV AB
END
Interfacing with
8051 Microcontroller
Images of 1) Push switch, 2) Relay, 3) Common Anode Type
7 Segment Display
Interfacing circuit for Push switch & LED
Glowing
Program to glow LEDs one by one in a sequence
continuously

DELAY: MOV R0,#10


ORG 0000H NXT 1 : MOV R1, #200
SJMP MAIN NXT 2 : MOV R2, #250
MAIN: MOV A, 0FEH NXT 3: DJNZ R2, NXT3
REPEAT: MOV P0,A DJNZ R1, NXT2
ACALL DELAY DJNZ R0, NXT1
RL A RET
SJMP REPEAT
END
Interfacing circuit for 7 Segment Display
Program Code to display numbers from 0 to 9
repeatedly

ORG 0000H NOP


SJMP MAIN NOP
MAIN: NOP NOP
REPEAT: MOV A, #00H DJNZ R6, NXT1
MOV DPTR, #100H DJNZ R5, NXT2
NXT: MOV R2,A INC A
MOVC A, @A+DPTR CJNE A,#0AH
MOV P0,A SJMP REPEAT
MOV A, R2
MOV R5,#200 ORG 100H
NXT2: MOV R6,#255 DB 88H, 0BEH,0C4H, 94H, 0B2H,
NXT1:NOP 91H,81H,0BCH,80H,90H

END
What is Relay ?
A relay is an electromechanical switch.
which perform ON and OFF operations
without any human interaction.

The relay consists a inductor coil, a spring ,


Swing terminal, and two high power contacts
named as normally closed (NC) and normally
opened (NO). Relay uses an Electromagnet to
move swing terminal between two contacts (NO
and NC). When there is no power applied to the
inductor coil (Relay is OFF), the spring holds the
swing terminal is attached to NC contact.
Whenever required power is applied to the
inductor coil, the current flowing through the coil
generates a magnetic field which is helpful to
move the swing terminal and attached it to the
normally open (NO) contact. Again when power
is OFF, the spring restores the swing terminal
position to NC
Interfacing circuit for Double Contact Relay
Program to CONTACT RELAY1 and RELAY 2

ORG 0000H
ORG 0000H SJMP MAIN
SJMP MAIN MAIN: MOV A, 0FCH/ 0FFH
MAIN: SETB P1.5 MOV P1,A
MAIN_LOOP: MOV C, P1.5 END
MOV P1.1,C
SJMP MAIN_LOOP
END

You might also like