Introduction to 8051 Programming

24
INTRODUCTION TO 8051 PROGRAMMING In this section we discuss Assembly language format and define some widely used terminology associated with Assembly language programming. While the CPU can work only in binary, it can do so at a very high speed. or humans, however, it is !uite tedious and slow to deal with "s and Is in order to program the computer. A  program that consists of "s and Is is called machine language. In the early days of the computer,  programmers coded programs in machine language. Although the he#adecimal system was used as a more efficient way to represent binary numbers, the process of working in machine code was still cumbersome for humans. $ventually, Assembly languages were developed that provided mnemonics for the machine code instructions, plus other features that made programming faster and less pr one to error. %he te rm mnemonic is fr e!uently used in comput er scie nce and engineering literature to refer to codes and abbreviations that are relatively easy to remember. Ass embl y langua ge program s mus t be trans lat ed int o mac hine code by a progra m cal led an assembler. Assembly language is referred to as a low-level language  because it d eals directly with the internal structure of the CPU. Structure of Assembly la!ua!e An Assembly language program consists of, among other things, a series of lines of Assembly language instructions. An Assembly language instruction consists of a mnemonic, optionally followed by one or two operands. %he operands are the data items being manipulated, and the mnemonics are the co mmands to the CPU, telling it what to do with those items.

Transcript of Introduction to 8051 Programming

Page 1: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 1/24

INTRODUCTION TO 8051 PROGRAMMING

In this section we discuss Assembly language format and define some widely used

terminology associated with Assembly language programming.

While the CPU can work only in binary, it can do so at a very high speed. or humans,

however, it is !uite tedious and slow to deal with "s and Is in order to program the computer. A

 program that consists of "s and Is is called machine language. In the early days of the computer,

 programmers coded programs in machine language. Although the he#adecimal system was used

as a more efficient way to represent binary numbers, the process of working in machine code was

still cumbersome for humans. $ventually, Assembly languages were developed that provided

mnemonics for the machine code instructions, plus other features that made programming faster and less prone to error. %he term mnemonic is fre!uently used in computer science and

engineering literature to refer to codes and abbreviations that are relatively easy to remember.

Assembly language programs must be translated into machine code by a program called

an assembler. Assembly language is referred to as a low-level language because it deals directly

with the internal structure of the CPU.

Structure of Assembly la!ua!e

An Assembly language program consists of, among other things, a series of lines of 

Assembly language instructions. An Assembly language instruction consists of a mnemonic,

optionally followed by one or two operands. %he operands are the data items being manipulated,

and the mnemonics are the commands to the CPU, telling it what to do with those items.

Page 2: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 2/24

T"# PROGRAM COUNT#R AND ROM

In this section we e#amine the role of the program counter &PC' register in e#ecuting an

()*+ program. We also discuss "- memory space for various ()*+ family members.

Pro!ram couter $ t%e 8051

Another important register in the ()*+ is the PC &program counter'. %he program counter 

 points to the address of the ne#t instruction to be e#ecuted. As the CPU fetches the opcode from

the program "-, the program counter is incremented to point to the ne#t instruction. %he

 program counter in the ()*+ is + bits wide. %his means that the ()*+ can access program

addresses )))) to /, a total of 01 bytes of code.

Plac$! co&e $ 'ro!ram ROM

%o get a better understanding of the role of the program counter in fetching and e#ecuting

a program, we e#amine the action of the program counter as each instruction is fetched and

e#ecuted. irst, we e#amine once more the list file of the sample program and how the code is

 placed in the "- of an ()*+ chip.

Page 3: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 3/24

G$(e t%e s%ort otes o &ata ty'es a& D$rect$(es)

8051 DATA T*P#S AND DIR#CTI+#S

In this section we look at some widely used data types and directives supported by the

()*+ assembler.

8051 &ata ty'e a& &$rect$(es

%he ()*+ microcontroller has only one data type. It is ( bits, and the si2e of each register

is also ( bits. It is the 3ob of the programmer to break down data larger than ( bits &)) to /, or

) to 4** in decimal' to be processed by the CPU.

D, -&ef$e byte.

%he 56 directive is the most widely used data directive in the assembler. It is used to

define the (7bit data. When 56 is used to define data, the numbers can be in decimal, binary,

he#, or A8CII formats. or decimal, the 959 after the decimal number is optional, but using 969

&binary' and 9/9 &he#adecimal' for the others is re!uired. egardless of which is used, the

assembler will convert the numbers into he#. %o indicate A8CII, simply place the characters in

!uotation marks &:like this:'. %he assembler will assign the A8CII code for the numbers or 

Page 4: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 4/24

characters automatically. %he 56 directive is the only directive that can be used to define A8CII

strings larger than two characters; therefore, it should be used for all A8CII data definitions.

ollowing are some 56 e#amples<

$ither single or double !uotes can be used around A8CII strings. %his can be useful for 

strings, which contain a single !uote such as 9":=eary9. 56 is also used to allocate memory in

 byte7si2ed chunks.

Assembler &$rect$(es

%he following are some more widely used directives of the ()*+.

ORG (origin)

%he "> directive is used to indicate the beginning of the address. %he number that

comes after "> can be either in he# or in decimal. If the number is not followed by /, it is

decimal and the assembler will convert it to he#. 8ome assemblers use 9. ">9 &notice the dot'

instead of 9">9 for the origin directive. Check your assembler.

 EQU (equate)

%his is used to define a constant without occupying a memory location. %he $?U

directive does not set aside storage for a data item but associates a constant value with a data

label so that when the label appears in the program, itp constant value will be substituted for the

label. %he following uses $?U for the counter constant and then the constant is used to load the

@ register.

Page 5: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 5/24

When e#ecuting the instruction 9-" @, ttC"UB%9, the register @ will be loaded

with the value 4* &notice the sign'. What is the advantage of using $?UD Assume that there is

a constant &a fi#ed value' used in many different places in the program, and the programmer 

wants to change its value throughout. 6y the use of $?U, the programmer can change it once

and the assembler will changeE all of its occurrences, rather than search the entire program trying

to find every occurrence.

 END directive

Another important pseudocode is the $B5 directive. %his indicates to the assembler the

end of the source &asm' file. %he $B5 directive is the last line of an ()*+ program, meaning that

in the source code anything after the $B5 directive is ignored by the assembler. 8ome

assemblers use 9. $B59 &notice the dot' instead

of 9$B59.

Rules for labels $ Assembly la!ua!e

6y choosing label names that are meaningful, a programmer can make a program mucheasier to read and maintain. %here are several rules that names must follow. irst, each label

name must be uni!ue. %he names used for labels in Assembly language programming consist of 

alphabetic letters in both uppercase and lowercase, the digits ) through F, and the special

characters !uestion mark &D', period &.', at &G', underline &H', and dollar sign &'. %he first

character of the label must be an alphabetic character. In other words it cannot be a number.

Page 6: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 6/24

$very assembler has some reserved words that must not be used as labels in the program.

oremost among the reserved words are the mnemonics for the instructions. or e#ample,

9-"9 and 9A559 are reserved since they are instruction mnemonics.

8051 I/O PROGRAMMING

In the ()*+ there are a total of four ports for IJ" operations. $#amining igure 07+, note

that of the 0) pins, a total of @4 pins are set aside for the four ports P", P= P4, and P@, where

each port takes ( pins. %he rest of the pins are designated as rt, >B5, K%A=+, K%A=4. 8%,

$A, A=$JP"> and P8$B.

I/O 'ort '$s a& t%e$r fuct$os

%he four ports P", Pi, P4, and P@ each use ( pins, making them (7bit ports. All the ports

upon $8$% are configured as inputs, ready to be used as input ports. When the first ) is writtento a port, it becomes an output. %o reconfigure it as an input, a + must be sent to the port. %o use

any of these ports as an input port, it must be programmed, as we will e#plain throughout this

section. irst, we describe each port.

Page 7: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 7/24

  $!ure ) 8051 P$ D$a!ram

Port 0

Port ) occupies a total of ( pins &pins @4 7@F'. It can be used for input or output. %o use

the pins of port ) as both input and output ports, each pin must be connected e#ternally to a l"17

Page 8: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 8/24

ohm pull7up resistor. %his is due to the fact that P" is an open drain, unlike PI, P4, and P@. Open

drain is a term used for -"8 chips in the same way that open collector is used for %%= chips. In

any system using the ()*+J*4 chip, we normally connect P" to pull7up resistors.

Port 0 as $'ut

With resistors connected to port ), in order to make it an input, the port must be programmed by

writing + to all the bits. In the following code, port ) is configured first as an input port by

writing Is to it, and then data is received from that port and sent to P+.

Port 1

Port + occupies a total of ( pins &pins + through ('. It can be used as input or output. In contrast

to port ), this port does not need any pull7up resistors since it already has pull7up resistors

internally. Upon reset, port + is configured as an input port. %he following code will continuously

send out to port + the alternating values **/ and AA/.

Page 9: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 9/24

Port 1 as $'ut

If port + has been configured as an output port, to make it an input port again, it must

 programmed as such by writing + to all its bits. %he reason for this is discussed in Appendi# C.4.

In the following code, port + is configured first as an input port by writing Is to it, then data is

received from that port and saved in L, , and *.

Port

Port 4 occupies a total of ( pins &pins 4+ through 4('. It can be used as input or output. Must like

PI, port 4 does not need any pull7up resistors since it already has pull7up resistors internally.

Page 10: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 10/24

Upon reset, port 4 is configured as an input port. %he following code will send out continuously

to port 4 the alternating values **/ and AA/. %hat is, all the bits of P4 toggle continuously.

Port as $'ut

%o make port 4 an input, it must programmed as such by writing + to all its bits. In the following

code, port 4 is configured first as an input port by writing + s to it. %hen data is received from

that port and is sent to PI continuously.

Dual role of 'ort

In many systems based on the ()*+, P4 is used as simple IJ". /owever, in ()@+7based

systems, port 4 must be used along with P" to provide the +7bit address for e#ternal memory.,

 port 4 is also designated as A( 7 A+*, indicating its dual function. 8ince an ()*+J@+ is capable of 

accessing 01 bytes of e#ternal memory, it needs a path for the + bits of the address. While P"

Page 11: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 11/24

 provides the lower ( bits via A" 7 AL, it is the 3ob of P4 to provide bits A( 7A+* of the address.

In other words, when the ()*+J@+ is connected to e#ternal memory, P4 is used for the upper (

 bits of the +7bit address.

ARIT"M#TIC INSTRUCTIONS AND PROGRAMS

Unsigned numbers are defined as data in which all the bits are used to represent

data, and no bits are set aside for the positive or negative sign. %his means that the

operand can be between )) and / &) to 4** decimal' for (7bit data.

A&&$t$o of us$!e& umbers

In the ()*+, in order to add numbers together, the accumulator register &A' must be

involved. %he form of the A55 instruction is

%he instruction A55 is used to add two operands. %he destination operand is always in

register A while the source operand can be a register, immediate data, or in memory.

emember that memory7to7memory arithmetic operations are never allowed in ()*+

Assembly language. %he instruction could change any of the A, C, or P bits of the flag

register, depending on the operands involved.

$#ample

8how how the flag register is affected by the following instructions.

Page 12: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 12/24

After the addition, register A &destination' contains )) and the flags are as follows<

CN O + since there is a carry out from 5L.

P O ) because the number of Is is 2ero &an even number'.

AC O + since there is a carry from 5@ to 50.

A&&$t$o of $&$($&ual bytes

$#ample

Assume that A- locations 0) 7 00 have the following values. Write a program to find the sum

of the values. At the end of the program, register A should contain the low byte and L the high

 byte. All values are in he#.

0)O&L5' 0+O&$6' 04O&C*' 0@O&*6' 00O&@)'

8olution<

Page 13: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 13/24

Subtract$o of us$!e& umbers

SU,, &subtract with borrow' when CNO)

In subtraction, the ()*+ microprocessors &indeed, all modern CPUs' use the 4:s

complement method. Although every CPU contains adder circuitry, it would be too

cumbersome &and take too many transistors' to design separate subtracter circuitry. or 

this reason, the ()*+ uses adder circuitry to perform the subtraction command. Assuming

that the ()*+ is e#ecuting a simple subtract instruction and that CN O ) prior to the

e#ecution of the instruction, one can summari2e the steps of the hardware of the CPU in

e#ecuting the 8U66 instruction for unsigned numbers, as follows.

+. %ake the 4:s complement of the subtrahend &source operand'.

4. Add it to the minuend &A'.

@. Invert the carry.

%hese three steps are performed for every 8U66 instruction by the internal hardware of the ()*+

CPU, regardless of the source of the operands, provided that the addressing mode is supported.

After these three steps the result is obtained and the flags are set.

Page 14: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 14/24

$#ample

UNSIGN#D MU2TIP2ICATION AND DI+ISION

In multiplying or dividing two numbers in the ()*+, the use of registers A and 6 is

re!uired since the multiplication and division instructions work only with these two registers. We

first discuss multiplication.

Mult$'l$cat$o of us$!e& umbers

%he ()*+ supports byte7by7byte multiplication only. %he bytes are assumed to be unsigned data.

%he synta# is as follows<

In byte7by7byte multiplication, one of the operands must be in register A, and the second operand

must be in register 6. After multiplication, the result is in the A and 6 registers; the lower byte is

Page 15: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 15/24

in A, and the upper byte is in 6. %he following e#ample multiplies 4*/ by */. %he result is a

+7bit data that is held by the A and 6 registers.

%able

D$($s$o of us$!e& umbers

In the division of unsigned numbers, the ()*+ supports byte over byte only. %he synta# is as

follows.

When dividing a byte by a byte, the numerator must be in register A and the denominator must

 be in 6. After the 5I instruction is performed, the !uotient is in A and the remainder is in 6.

8ee the following e#ample.

 Botice the following points for instruction 95I A69<

%his instruction always makes CN O ) and " O ) if the denominator is not ).

Page 16: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 16/24

If the denominator is ) &6 O )', " O + indicates an error, and CN O ). %he standard practice in

all microprocessors when dividing a number by ) is to indicate in some way the invalid result of

infinity. In the ()*+, the " flag is set to +.

%able < Unsigned 5ivision 8ummary &5I A6'

2OGIC INSTRUCTIONS AND PROGRAMS

Apart from IJ" and arithmetic instructions, logic instructions are some of most widely

used instructions. In this section we cover 6oolean logic instructions such as AB5, ",

e#clusive7or &K"', and complement. We will also study the compare instruction.

AND

%his instruction will perform a logical AB5 on the two operands and place the result in

the destination. %he destination is normally the accumulator. %he source operand can be a

register, in memory, or immediate. . %he AB= instruction for byte7si2e operands has no effect on

any of the flags. %he AB= instruction is often used to mask &set to )' certain bits of an operand.

8ee following $#ample.

Page 17: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 17/24

2o!$cal AND uct$o

OR 

2o!$cal OR uct$o

"= destination,source ;dest O dest " source

%he destination and source operands are "ed, and the result is placed in the destination. %he

"= instruction can be used to set certain bits of an operand to +. %he destination is normally the

accumulator. %he source operand can be a register, in memory, or immediate. 8ee Appendi# A for 

Page 18: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 18/24

more on the addressing modes supported by this instruction. %he "= instruction for byte7si2e

operands has no effect on any of the flags

3OR 

K= destination,source ;dest O dest K" source

%his instruction will perform the K" operation on the two operands, and place the result in the

destination. %he destination is normally the accumulator. %he source operand can =ogical K?

unction be a register, in memory, or immediate. 8ee Appendi# A.I for the addressing modes of

this instruction. %he K= instruction for byte7si2e operands has no effect on any of the flags.

K= can also be used to see if two registers have the same value. 9K= A, l9 will

e#clusive7or register A and register l, and put the result in A. If both registers have the same

value, )) is placed in A.

Page 19: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 19/24

%he K= instruction can be used to clear the contents of a register by K"ing it

with itself. 8how how 9K= A, A9 clears A, assuming that A O 0*/.

DATA T*P#S AND TIM# D#2A* PROGRAM IN C

Compilers produce he# files that we download into the "- of the microcontroller. %he

si2e of the he# file produced by the compiler is one of the main concerns of microcontroller 

 programmers, for two reasons<

Page 20: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 20/24

+. -icrocontrollers have limited on7chip "-.

4. %he code space for the ()*+ is limited to 01 bytes.

/ow does the choice of programming language affect the compiled program si2eD While

Assembly language produces a he# file that is much smaller than C, programming in Assembly

language is tedious and time consuming. C programming, on the other hand, is less time

consuming and much easier to write, but the he# file si2e produced is much larger than if we

used Assembly language. %he following are some of the ma3or reasons for writing programs in C

instead of Assembly<

+. It is easier and less time consuming to write in C than Assembly.

4. C is easier to modify and update.

@. Nou can use code available in function libraries.

0. C code is portable to other microcontrollers with little or no modification.

5iscuss about 5ata types and time delay in ()*+C.

DATA T*P#S AND TIM# D#2A* IN 8051 C

C &ata ty'es for t%e 8051

8ince one of the goals of ()*+ C programmers is to create smaller he# files, it is worthwhile to

re7e#amine C data types for ()*+ C. In other words, a good understanding of C data types for the

()*+ can help programmers to create smaller he# files. In this section we focus on the specific C

data types that are most useful and widely used for the ()*+ microcontroller.

Us$!e& c%ar

8ince the ()*+ is an (7bit microcontroller, the character data type is the most natural choice for

many applications. %he unsigned char is an (7bit data type that takes a value in the range of ) 7

4** &)) 7 /'. It is one of the most widely used data types for the ()*+. In many situations,

such as setting a counter value.

In declaring variables, we must pay careful attention to the si2e of the data and try to use

unsigned char instead of int if possible. 6ecause the ()*+ has a limited number of registers and

data A- locations, using the int in place of the char data type can lead to a larger si2e he# file.

8uch a misuse of the data types in compilers such as -icrosoft isual C for #( I6- PCs is

not a significant issue.

Page 21: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 21/24

$#ample

un the above program on your simulator to see how PI displays values @)/, @+/, @4/. @@/.

@0/. @*/. 0+/. 04/, 0@/, and 00/, the he# values for A8CII ), +, 4, and so on.

S$!e& c%ar

%he signed char is an (7bit data type that uses the most significant bit &5L of 5L 7

5"' to represent the 7 or value. As a result, we have only L bits for the magnitude of

the signed number, giving us values from 7+4( to +4L. In situations where and 7 are needed to

represent a given !uantity such as temperature, the use of the signed char data type is a must.

Again notice that if we do not use the keyword unsigned, the default is the signed value. or that

reason we should stick with the unsigned char unless the data needs to be represented as signed

numbers.

#4am'le

un the above program on your simulator to see how PI displays values of +, /, 4, $/, @,

5/, 0, and C/, the he# values for Q,7Q, 4, 74, and so on.

Page 22: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 22/24

I/O PROGRAMMING IN 8051 C

In this section we look at C programming of the IJ" ports for the ()*+. We look at both

 byte and bit IJ" programming.

,yte s$e I/O

=$5s are connected to bits PI and P4. Write an ()*+ C program that shows the count from ) to

/ &)))) )))) to ++++ ++++ in binary' on the =$5s.

8olution<

,$t6a&&ressable I/O 'ro!ramm$!

%he IJ" ports of P" 7 P@ are bit7addressable. We can access a single bit without disturbing the

rest of the port. We use the sbit data type to access a single bit of P" 7 P@:. "ne way to do that is

to use the P#Ay format where x is the port ), +, 4, or @, and y is the bit ) 7 L of that port.

#4am'le

Write an ()*+ C program to toggle only bit P4.0 continuously without disturbing the rest of the

 bits of P4.

8olution<

Page 23: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 23/24

5iscuss About logical and arithmetic oerations in ()*+C.

2OGIC AND ARIT"M#TIC OP#RATIONS IN 8051 C

"ne of the most important and powerful features of the C language is its ability to

 perform bit manipulation. %his section describes the action of bit7wise logic operators and

 provides some e#amples of how they are used.

,$t67$se o'erators $ C

While every C programmer is familiar with the logical operators AB5 &RR', " &SS', and

 B"% &Q', many C programmers are less familiar with the bitwise operators AB5 &R', " &S', $K7

" &A', Inverter &T', 8hift ight &', and 8hift =eft &V'. %hese bit7wise operators are widely used

in software engineering for embedded systems and control; conse!uently, understanding and

mastery of them are critical in microprocessor7based system design and interfacing. 8ee %able .

%able < 6it7wise =ogic "perators for C

Page 24: Introduction to 8051 Programming

7/23/2019 Introduction to 8051 Programming

http://slidepdf.com/reader/full/introduction-to-8051-programming 24/24

6asic registers of timer programming ()*+ timer counter

 programming basics of serial communication ()*+ connection to 8 4@4

  ()*+ serial communication. Programming ()*+ interrupts  

 programming e#ternal hardware interrupts.