You are on page 1of 64

SECTION 1.

2: OVERVIEW OF THE 8051 FAMILY


In this section we first look at the various members of the 8051 family of microcontrollers and their internal features. Plus we see who are the different manufacturers of the 8051 and what kind of products they offer.

A brief history of the 8051


In 1981, Intel Corporation introduced an 8-bit microcontroller called the 8051. This microcontroller had 128 bytes of RAM, 4K bytes of on-chip ROM, two timers, one serial port, and four ports (each 8-bits wide) all on a single chip. At the time it was also referred to as a "system on a chip." The 8051 is an 8-bit processor, meaning that the CPU can work on only 8 bits of data at a time. Data larger than 8 bits has to be broken into 8-bit pieces to be processed by the CPU. The 8051 has a total of four I/O ports, each 8 bits wide. See Figure 1-2. Although the 8051 can have a maximum of 64K bytes of on-chip ROM, many manufacturers have put only 4K bytes on the chip. This will be discussed in more detail later.

Table 1-3: Features of the 8051

The 8051 became widely popular after Intel allowed other manufacturers to make and market any flavors of the 8051 they please with the condition that they remain code-compatible with the 8051. This has led to many, versions of the 8051 with different speeds and amounts of on-chip ROM marketed by more than half a dozen manufacturers. Next we review some of them. It is important to note that although there are different flavors of the 8051 in terms of speed and amount of on-chip ROM, they are all compatible with the original 8051 as far as the instructions are concerned. This means that if you write your program for one, it will run on any of them regardless of the manufacturer.

8051 microcontroller

The 8051 is the original member of the 8051 family. Intel refers to it as MCS-51. Table 1-3 shows the main features of the 8051.

Figure 1-2. Inside the 8051 Microcontroller Block Diagram

INSIDE THE 8051


In Section 2.1 we look at the inside of the 8051. We demonstrate some of the widely used registers of the 8051 with simple instructions such as MOV and ADD. In Section 2.2 we examine. Assembly language and machine language programming and define terms such as mnemonics, opcode, operand, etc. The process of assembling and creating a ready-to-run program for the 8051 is discussed in Section 2.3. Step-by-step execution of an 8051 program and the role of the program counter are examined in Section 2.4. In Section 2.5 we look at some widely used Assembly language directives, pseudocode, and data types related to the 8051. In Section 2.6 we discuss the flag bits and how they are affected by arithmetic instructions. Allocation of RAM memory inside the 8051 plus the stack and register banks of the 8051 are discussed in Section 2.7. SECTION 2.1: INSIDE THE 8051

In this section we examine the major registers of the 8051 and show their use with the simple instructions MOV and ADD. Registers

In the CPU, registers are used to store information temporarily. That information could be a byte of data to be processed, or an address pointing to the data to be fetched. The vast majority of 8051 registers are 8-bit registers. In the 8051 there is only one data type: 8 bits. The 8 bits of a register are shown in the diagram from the MSB (most significant bit) D7 to the LSB (least significant bit) DO. With an 8-bit data type, any data larger than 8 bits must be broken into 8-bit chunks before it is processed. Since there are a large number of registers in the 8051, we will concentrate on some of the widely used generalpurpose registers and cover special registers in future chapters. See Appendix A.2 for a complete list of 8051 registers.

Figure 2-1 (a). Some 8-bit Registers of the 8051

Figure 2-1 (b). Some 8051 16-bit Registers The most widely used registers of the 8051 are A (accumulator), B, RO, Rl, R2, R3, R4, R5, R6, R7, DPTR (data pointer), and PC (program counter). All of the above registers are 8-bits, except DPTR and the program counter. The accumulator, register A, is used for all arithmetic and logic instructions. To understand the use of these registers, we will show them in the context of two simple instructions, MOV and ADD. MOV instruction Simply stated, the MOV instruction copies data from one location to another. It has the following format: MOV destination,source ;copy source to dest. This instruction tells the CPU to move (in reality, copy) the source operand to the destination operand. For example, the instruction "MOV A, RO" copies the contents of register RO to register A. After this instruction is executed, register A will have the same value as register RO. The MOV instruction does not affect the source operand. The following program first loads register A with value 55H (that is 55 in hex), then moves this value around to various registers inside the CPU. Notice the "#" in the instruction. This signifies that it is a value. The importance of this will be discussed soon. MOV A,#55H ;load value 55H into reg. A MOV RO,A ;copy contents of A into RO ;(now A=RO=55H) MOV R1,A ,-copy contents of A into Rl

;(now A=RO=R1=55H) MOV R2,A ;copy contents of A into R2 ;now A=RO=R1=R2=55H) MOV R3,#95H ;load value 95H into R3 ;(now R3=95H) MOV A,R3 /copy contents of R3 into A ;now A=R3=95H) When programming the 8051 microcontroller, the following points should be noted: 1. Values can be loaded directly into any of registers A, B, or RO - R7. However, to indicate that it is an immediate value it must be preceded with a pound sign (#). This is shown next. MOV A,#23H ;load 23H into A (A=23H) MOV RO,#12H ;load 12H into RO (RO=12H) MOV R1,#1FH ;load 1FH into Rl (R1=1FH) MOV R2,#2BH ;load 2BH into R2 (R2=2BH) MOV B,#3CH ;load 3CH into B (B=3CH) MOV R7,#9DH ;load 9DH into R7 (R7=9DH) MOV R5,#OF9H ;load F9H into R5 (R5=F9H) MOV R6,#12 ,-load 12 decimal (OCH) ,-into reg. R6 (R6 = OCH)

Notice in instruction "MOV R5 , #0F9H" that a 0 is used between the # and F to indicate that F is a hex number and not a letter. In other words "MOV R5 , #F9H" will cause an error.

1.

If values 0 to F are moved into an 8-bit register, the rest of the bits are assumed to be all zeros. For example, in "MOV A, #5" the result will be A = 05; that is, A = 00000101 in binary.

1.

Moving a value that is too large into a register will cause an error. MOV A,#7F2H ;ILLEGAL: 7F2H > 8 bits (FFH) MOV R2,#456 ;ILLEGAL: 456 > 255 decimal (FFH) 4. A value to be loaded into a register must be preceded with a pound sign (#). Otherwise it means to load from a memory location. For example "MOV A, 17H" means to move into A the value held in memory location 17H, which could have any value. In order to load the value 17H into the accumulator we must write "MOV A, #17H" with the # preceding the number. Notice that the absence of the pound sign will not cause an error by the assembler since it is a valid instruction. However, the result would not be what the programmer intended. This is a common error for beginning programmers in the 8051.

ADD instruction The ADD instruction has the following format: ADD A,source ;ADD the source operand ;to the accumulator The ADD instruction tells the CPU to add the source byte to register A and put the result in register A. To add two numbers such as 25H and 34H, each can be moved to a register and then added together:

MOV A,#25H /load 25H into A MOV R2,#34H ;load 34H into R2 ADD A,R2 /add R2 to accumulator ; (A = A + R2) Executing the. program above results in A - 59H (25H + 34H = 59H) and R2 = 34H. Notice that the content of R2 does not change. The program above can be written in many ways, depending on the registers used. Another way might be: MOV R5,#25H ;load 25H into R5 (R5=25H) MOV R7,#34H ;load 34H into R7 (R7=34H) MOV A,#0 /load 0 into A (A=0,clear A) ADD A,R5 ;add to A content of R5 ; where A = A + R5 ADD A,R7 /add to A content of R7 ; where A = A + R7 The program above results in A = 59H. There are always many ways to write the same program. One question that might come to mind after looking at the program above, is whether it is necessary to move both data items into registers before adding them together. The answer is no, it is not necessary. Look at the following variation of the same program: MOV A,#25H ;load one operand into A (A=25H) ADD A,#34H ;add the second operand 34H to A In the above case, while one register contained one value, the second value followed the instruction as an operand. This is called an immediate operand. The examples shown so far for the ADD instruction indicate that the source operand can be either a register or immediate data, but the destination must always be register A, the accumulator. In other words, an instruction such as "ADD R2 , #12H" is invalid since register A (accumulator) must be involved in any arithmetic operation. Notice that "ADD R4, A" is also invalid for the reason that A must be the destination of any arithmetic operation. To put it simply: In the 8051, register A must be involved and be the destination for all arithmetic operations. The foregoing discussion explains why register A is referred to as the accumulator. The format for Assembly language instructions, descriptions of their use, and a listing of legal operand types are provided in Appendix A. 1.

There are two 16-bit registers in the 8051: PC (program counter) and DPTR (data pointer). The importance and use of the program counter are covered in Section 2.3. The DPTR register is used in accessing data and is discussed in Chapter 5 where addressing modes are covered. SECTION 2.2: INTRODUCTION TO 8051 ASSEMBLY 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. For humans, however, it is quite tedious and slow to deal with Os and Is in order to program the computer. A program that consists of Os and Is is called machine language. In the early days of the computer, programmers coded programs in machine language. Although the hexadecimal system was used as a more efficient way to represent binary numbers, the process of working in machine code was still cumbersome for humans. Eventually, Assembly languages were developed that provided mnemonics for the machine code instructions, plus other features that made programming faster and less prone to error. The term mnemonic is frequently 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 anassembler. Assembly language is referred to as a low-level language because it deals directly with the internal structure of the CPU. To program in Assembly language, the programmer must know all the registers of the CPU and the size of each, as well as other details. Today, one can use many different programming languages, such as BASIC, Pascal, C, C++, Java, and numerous others. These languages are called high-level languages because the programmer does not have to be concerned with the internal details of the CPU. Whereas an assembler is used to translate an Assembly language program into machine code (sometimes also called object code or opcode for operation code), high-level languages are translated into machine code by a program called a compiler.For instance, to write a program in C, one must use a C compiler to translate the program into machine language. Now we look at 8051 Assembly language format and use an 8051 assembler to create a ready-to-run program.

Structure of Assembly language 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. The operands are the data items being manipulated, and the mnemonics are the commands to the CPU, telling it what to do with those items.

Program 2-1: Sample of an Assembly Language Program SECTION 2.4: THE PROGRAM COUNTER AND ROM SPACE IN THE 8051 In this section we examine the role of the program counter (PC) register in executing an 8051 program. We also discuss ROM memory space for various 8051 family members. Program counter in the 8051 Another important register in the 8051 is the PC (program counter). The program counter points to the address of the next instruction to be executed. As the CPU fetches the opcode from the program ROM, the program counter is incremented to point to the next instruction. The program counter in the 8051 is 16 bits wide. This means that the 8051 can access program addresses 0000 to FFFFH, a total of 64K bytes of code. However, not all members of the 8051 have the entire 64K bytes of on-chip ROM installed, as we will see soon. Where does the 8051 wake up when it is powered? We will discuss this important topic next. Where the 8051 wakes up when it is powered up One question that we must ask about any microcontroller (or microprocessor) is: At what address does the CPU wake up upon applying power to it? Each microprocessor is different. In the case of the 8051 family (that is, all members regardless of the maker and variation), the microcontroller wakes up at memory address 0000 when it is powered up. By powering up we mean applying Vcc to the RESET pin as discussed in Chapter 4. In other words, when the 8051 is powered up,.the PC (program counter) has the value of 0000 in it. This means that it expects the first opcode to be stored at ROM address OOOOH. For this reason in the 8051 system, the first opcode must be burned into memory location OOOOH of program ROM since this is where it looks for the first instruction when it is booted. We achieve this by the ORG statement in the source program as shown earlier.

Assembler directives The following are some more widely used directives of the 8051. ORG (origin) The ORG directive is used to indicate the beginning of the address. The number that comes after ORG can be either in hex or in decimal. If the number is not followed by H, it is decimal and the assembler will convert it to hex. Some assemblers use ". ORG" (notice the dot) instead of "ORG" for the origin directive. Check your assembler. EQU (equate) This is used to define a constant without occupying a memory location. The EQU 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. The following uses EQU for the counter constant and then the constant is used to load the R3 register.

When executing the instruction "MOV R3, ttCOUNT", the register R3 will be loaded with the value 25 (notice the # sign). What is the advantage of using EQU? Assume that there is a constant (a fixed value) used in many different places in the program, and the programmer wants to change its value throughout. By the use of EQU, the programmer can change it once and the assembler will change* all of its occurrences, rather than search the entire program trying to find every occurrence. END directive Another important pseudocode is the END directive. This indicates to the assembler the end of the source (asm) file. The END directive is the last line of an 8051 program, meaning that in the source code anything after the END directive is ignored by the assembler. Some assemblers use ". END" (notice the dot) instead of "END". SECTION 2.6: 8051 FLAG BITS AND THE PSW REGISTER

Like any other microprocessor, the 8051 has a flag register to indicate arithmetic conditions such as the carry bit. The flag register in the 8051 is called the program status word (PSW) register. In this section we discuss various bits of this register and provide some examples of how it is altered. PSW (program status word) register The program status word (PSW) register is an 8-bit register. It is also referred to as the flag register.Although the PSW register is 8 bits wide, only 6 bits of it are used by the 8051. The two unused bits are user-definable flags. Four of the flags are called conditional flags, meaning that they indicate some conditions that result after an instruction is executed. These four are CY (carry), AC (auxiliary carry), P (parity), and OV (overflow). As seen from Figure 2-4, the bits PSW.3 and PSW.4 are designated as RSO and RSI, respectively, and are used to change the bank registers. They are explained in the next section. The PSW.5 and PSW.l bits are general-purpose status flag bits and can be used by the programmer for any purpose. In other words, they are user definable. See Figure 2-4 for the bits of the PSW register.

Figure 2-4. Bits of the PSW Register

2 Pinout Description
Pins 1-8: Port 1 Each of these pins can be configured as an input or an output. Pin 9: RS A logic one on this pin disables the microcontroller and clears the contents of most registers. In other words, the positive voltage on this pin resets the microcontroller. By applying logic zero to this pin, the program starts execution from the beginning. Pins10-17: Port 3 Similar to port 1, each of these pins can serve as general input or output. Besides, all of them have alternative functions: Pin 10: RXD Serial asynchronous communication input or Serial synchronous communication output. Pin 11: TXD Serial asynchronous communication output or Serial synchronous communication clock output. Pin 12: INT0 Interrupt 0 input. Pin 13: INT1 Interrupt 1 input. Pin 14: T0 Counter 0 clock input. Pin 15: T1 Counter 1 clock input. Pin 16: WR Write to external (additional) RAM. Pin 17: RD Read from external RAM. Pin 18, 19: X2, X1 Internal oscillator input and output. A quartz crystal which specifies operating frequency is usually connected to these pins. Instead of it, miniature ceramics resonators can also be used for frequency stability. Later versions of microcontrollers operate at a frequency of 0 Hz up to over 50 Hz.

Pin 20: GND Ground. Pin 21-28: Port 2 If there is no intention to use external memory then these port pins are configured as general inputs/outputs. In case external memory is used, the higher address byte, i.e. addresses A8-A15 will appear on this port. Even though memory with capacity of 64Kb is not used, which means that not all eight port bits are used for its addressing, the rest of them are not available as inputs/outputs. Pin 29: PSEN If external ROM is used for storing program then a logic zero (0) appears on it every time the microcontroller reads a byte from memory. Pin 30: ALE Prior to reading from external memory, the microcontroller puts the lower address byte (A0-A7) on P0 and activates the ALE output. After receiving signal from the ALE pin, the external register (usually 74HCT373 or 74HCT375 add-on chip) memorizes the state of P0 and uses it as a memory chip address. Immediately after that, the ALU pin is returned its previous logic state and P0 is now used as a Data Bus. As seen, port data multiplexing is performed by means of only one additional (and cheap) integrated circuit. In other words, this port is used for both data and address transmission. Pin 31: EA By applying logic zero to this pin, P2 and P3 are used for data and address transmission with no regard to whether there is internal memory or not. It means that even there is a program written to the microcontroller, it will not be executed. Instead, the program written to external ROM will be executed. By applying logic one to the EA pin, the microcontroller will use both memories, first internal then external (if exists). Pin 32-39: Port 0 Similar to P2, if external memory is not used, these pins can be used as general inputs/outputs. Otherwise, P0 is configured as address output (A0-A7) when the ALE pin is driven high (1) or as data output (Data Bus) when the ALE pin is driven low (0). Pin 40: VCC +5V power supply.

2.3 Input/Output Ports (I/O Ports)


All 8051 microcontrollers have 4 I/O ports each comprising 8 bits which can be configured as inputs or outputs. Accordingly, in total of 32 input/output pins enabling the microcontroller to be connected to peripheral devices are available for use. Pin configuration, i.e. whether it is to be configured as an input (1) or an output (0), depends on its logic state. In order to configure a microcontroller pin as an input, it is necessary to apply a logic zero (0) to appropriate I/O port bit. In this case, voltage level on appropriate pin will be 0.

Similarly, in order to configure a microcontroller pin as an input, it is necessary to apply a logic one (1) to appropriate port. In this case, voltage level on appropriate pin will be 5V (as is the case with any TTL input). This may seem confusing but don't loose your patience. It all becomes clear after studying simple electronic circuits connected to an I/O pin.

LOOP AND JUMP INSTRUCTIONS in 8051


In the sequence of instructions to be executed, it is often necessary to transfer program control to a different location. There are many instructions in the 8051 to achieve this. This chapter covers the control transfer instructions available in 8051 Assembly language. In the first section we discuss instructions used for looping, as well as instructions for conditional and unconditional jumps. In the second section we examine CALL instructions and their uses. In the third section, time delay subroutines are described for both the traditional 8051 and its newer generation. SECTION 3.1: LOOP AND JUMP INSTRUCTIONS In this section we first discuss how to perform a looping action in the 8051 and then talk about jump instructions, both conditional and unconditional. Looping in the 8051 Repeating a sequence of instructions a certain number of times is called a loop. The loop is one of most widely used actions that any microprocessor performs. In the 8051, the loop action is performed by the instruction "DJNZ reg, label". In this instruction, the register is decremented; if it is not zero, it jumps to the target address referred to by the label. Prior to the start of the loop the register is loaded with the counter for the number of repetitions. Notice that in this instruction both the register decrement and the decision to jump are combined into a single instruction. Example 3-1

In the program in Example 3-1, the R2 register is used as a counter. The counter is first set to 10. In each iteration the instruction DJNZ decrements R2 and checks its value. If R2 is not zero, it jumps to the target address associated with the label "AGAIN". This.looping action continues until R2 becomes zero. After R2 becomes zero, it falls through the loop and executes the instruction immediately below it, in this case the "MOV R5 , A" instruction. Notice in the DJNZ instruction that the registers can be any of RO - R7. The counter can also be a RAM location as we will see in Chapter 5. Write a program to (a) load the accumulator with the value 55H, and (b) complement the ACC 700 times. Solution: 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 to use R2 and R3 for the count.

SECTION 3.2: CALL INSTRUCTIONS Another control transfer instruction is the CALL instruction, which is used to call a subroutine. Subroutines are often used to perform tasks that need to be performed frequently. This makes a program more structured in addition to saving memory space. In the 8051 there are two instructions for call: LCALL (long call) and ACALL (absolute call). Deciding which one to use depends on the target address. Each instruction is explained next.

LCALL (long call) In this 3-byte instruction, the first byte is the opcode and the second and third bytes are used for the address of the target subroutine. Therefore, LCALL can be used to call subroutines located anywhere within the 64K-byte address space of the 8051. To make sure that after execution of the called subroutine the 8051 knows where to come back to, the processor automatically saves on the stack the address of the instruction immediately below the LCALL. When a subroutine is called, control is transferred to that subroutine, and the processor saves the PC (program counter) on the stack and begins to fetch instructions from the new location. After finishing execution of the subroutine, the instruction RET (return) transfers control back to the caller. Every subroutine needs RET as the last instruction. See Example 3-8. The following points should be noted for the program in Example 3-8. 1. Notice the DELAY subroutine. Upon executing the first "LCALL DELAY", the address of the instruction right below it, "MOV A, #OAAH", is pushed onto the stack, and the 8051 starts to execute instructions at address 300H. 2. In the DELAY subroutine, first the counter R5 is set to 255 (R5 = FFH); there fore, the loop is repeated 256 times. When R5 becomes 0, control falls to the RET instruction, which pops the address from the stack into the program counter and resumes executing the instructions after the CALL. SECTION 3.2: CALL INSTRUCTIONS Another control transfer instruction is the CALL instruction, which is used to call a subroutine. Subroutines are often used to perform tasks that need to be performed frequently. This makes a program more structured in addition to saving memory space. In the 8051 there are two instructions for call: LCALL (long call) and ACALL (absolute call). Deciding which one to use depends on the target address. Each instruction is explained next. LCALL (long call) In this 3-byte instruction, the first byte is the opcode and the second and third bytes are used for the address of the target subroutine. Therefore, LCALL can be used to call subroutines located anywhere within the 64K-byte address space of the 8051. To make sure that after execution of the called subroutine the 8051 knows where to come back to, the processor automatically saves on the stack the address of the instruction immediately below the LCALL. When a subroutine is called, control is transferred to that subroutine, and the processor saves the PC (program counter) on the stack and begins to fetch instructions from the new location. After finishing execution of the subroutine, the instruction RET (return) transfers control back to the caller. Every subroutine needs RET as the last instruction. See Example 3-8. The following points should be noted for the program in Example 3-8.

1.

Notice the DELAY subroutine. Upon executing the first "LCALL DELAY", the address of the instruction right below it, "MOV A, #OAAH", is pushed onto the stack, and the 8051 starts to execute instructions at address 300H. 2. In the DELAY subroutine, first the counter R5 is set to 255 (R5 = FFH); there fore, the loop is repeated 256 times. When R5 becomes 0, control falls to the RET instruction, which pops the address from the stack into the program counter and resumes executing the instructions after the CALL. A developer is using the Atmel AT89C1051 microcontroller chip for a product. This chip has only IK byte of on-chip flash ROM. Which instruction, LCALL or ACALL, is more useful in programming this chip? Solution: The ACALL instruction is more useful since it is a 2-byte instruction. It saves one byte each time the call instruction is used.

2.3 Input/Output Ports (I/O Ports)


All 8051 microcontrollers have 4 I/O ports each comprising 8 bits which can be configured as inputs or outputs. Accordingly, in total of 32 input/output pins enabling the microcontroller to be connected to peripheral devices are available for use. Pin configuration, i.e. whether it is to be configured as an input (1) or an output (0), depends on its logic state. In order to configure a microcontroller pin as an input, it is necessary to apply a logic zero (0) to appropriate I/O port bit. In this case, voltage level on appropriate pin will be 0. Similarly, in order to configure a microcontroller pin as an input, it is necessary to apply a logic one (1) to appropriate port. In this case, voltage level on appropriate pin will be 5V (as is the case with any TTL input). This may seem confusing but don't loose your patience. It all becomes clear after studying simple electronic circuits connected to an I/O pin.

Input/Output (I/O) pin Figure above illustrates a simplified schematic of all circuits within the microcontroler connected to one of its pins. It refers to all the pins except those of the P0 port which do not have pull-up resistors built-in.

Output pin A logic zero (0) is applied to a bit of the P register. The output FE transistor is turned on, thus connecting the appropriate pin to ground.

Input pin A logic one (1) is applied to a bit of the P register. The output FE transistor is turned off and the appropriate pin remains connected to the power supply voltage over a pull-up resistor of high resistance.

Logic state (voltage) of any pin can be changed or read at any moment. A logic zero (0) and logic one (1) are not equal. A logic one (0) represents a short circuit to ground. Such a pin acts as an output. A logic one (1) is loosely connected to the power supply voltage over a resistor of high resistance. Since this voltage can be easily reduced by an external signal, such a pin acts as an input. Port 0 The P0 port is characterized by two functions. If external memory is used then the lower address byte (addresses A0-A7) is applied on it. Otherwise, all bits of this port are configured as inputs/outputs. The other function is expressed when it is configured as an output. Unlike other ports consisting of pins with built-in pull-up resistor connected by its end to 5 V power supply, pins of this port have this resistor left out. This apparently small difference has its consequences:

If any pin of this port is configured as an input then it acts as if it floats. Such an input has unlimited input resistance and indetermined potential.

When the pin is configured as an output, it acts as an open drain. By applying logic 0 to a port bit, the appropriate pin will be connected to ground (0V). By applying logic 1, the external output will keep on floating. In order to apply logic 1 (5V) on this output pin, it is necessary to built in an external pull-up resistor.

Only in case P0 is used for addressing external memory, the microcontroller will provide internal power supply source in order to supply its pins with logic one. There is no need to add external pull-up resistors. Port 1 P1 is a true I/O port, because it doesn't have any alternative functions as is the case with P0, but can be cofigured as general I/O only. It has a pull-up resistor built-in and is completely compatible with TTL circuits. Port 2 P2 acts similarly to P0 when external memory is used. Pins of this port occupy addresses intended for external memory chip. This time it is about the higher address byte with addresses A8-A15. When no memory is added, this port can be used as a general input/output port showing features similar to P1. Port 3 All port pins can be used as general I/O, but they also have an alternative function. In order to use these alternative functions, a logic one (1) must be applied to appropriate bit of the P3 register. In tems of hardware, this port is similar to P0, with the difference that its pins have a pull-up resistor built-in.

A Register (Accumulator)

A register is a general-purpose register used for storing intermediate results obtained during operation. Prior to executing an instruction upon any number or operand it is necessary to store it in the accumulator first. All results obtained from arithmetical operations performed by the ALU are stored in the accumulator. Data to be moved from one register to another must go through the accumulator. In other words, the A register is the most commonly used register and it is impossible to imagine a microcontroller without it. More than half instructions used by the 8051 microcontroller use somehow the accumulator. B Register Multiplication and division can be performed only upon numbers stored in the A and B registers. All other instructions in the program can use this register as a spare accumulator (A).

During the process of writing a program, each register is called by its name so that their exact addresses are not of importance for the user. During compilation, their names will be automatically replaced by appropriate addresses. R Registers (R0-R7)

This is a common name for 8 general-purpose registers (R0, R1, R2 ...R7). Even though they are not true SFRs, they deserve to be discussed here because of their purpose. They occupy 4 banks within RAM. Similar to the accumulator, they are used for temporary storing variables and intermediate results during operation. Which one of these banks is to be active depends on two bits of the PSW Register. Active bank is a bank the registers of which are currently used. The following example best illustrates the purpose of these registers. Suppose it is necessary to perform some arithmetical operations upon numbers previously stored in the R registers: (R1+R2) - (R3+R4). Obviously, a register for temporary storing results of addition is needed. This is how it looks in the program: MOV A,R3; Means: move number from R3 into accumulator ADD A,R4; Means: add number from R4 to accumulator (result remains in accumulator) MOV R5,A; Means: temporarily move the result from accumulator into R5 MOV A,R1; Means: move number from R1 to accumulator ADD A,R2; Means: add number from R2 to accumulator SUBB A,R5; Means: subtract number from R5 (there are R3+R4)

Program Status Word (PSW) Register

PSW register is one of the most important SFRs. It contains several status bits that reflect the current state of the CPU. Besides, this register contains Carry bit, Auxiliary Carry, two register bank select bits, Overflow flag, parity bit and user-definable status flag. P - Parity bit. If a number stored in the accumulator is even then this bit will be automatically set (1), otherwise it will be cleared (0). It is mainly used during data transmit and receive via serial communication. - Bit 1. This bit is intended to be used in the future versions of microcontrollers. OV Overflow occurs when the result of an arithmetical operation is larger than 255 and cannot be stored in one register. Overflow condition causes the OV bit to be set (1). Otherwise, it will be cleared (0). RS0, RS1 - Register bank select bits. These two bits are used to select one of four register banks of RAM. By setting and clearing these bits, registers R0-R7 are stored in one of four banks of RAM. RS1 0 0 1 1 RS2 0 1 0 1 Space in RAM Bank0 00h-07h Bank1 08h-0Fh Bank2 10h-17h Bank3 18h-1Fh

F0 - Flag 0. This is a general-purpose bit available for use. AC - Auxiliary Carry Flag is used for BCD operations only. CY - Carry Flag is the (ninth) auxiliary bit used for all arithmetical operations and shift instructions. Data Pointer Register (DPTR) DPTR register is not a true one because it doesn't physically exist. It consists of two separate registers: DPH (Data Pointer High) and (Data Pointer Low). For this reason it may be treated as a 16-bit register or as two independent 8-bit registers. Their 16 bits are primarly used for external memory addressing.

Besides, the DPTR Register is usually used for storing data and intermediate results.

Stack Pointer (SP) Register

A value stored in the Stack Pointer points to the first free stack address and permits stack availability. Stack pushes increment the value in the Stack Pointer by 1. Likewise, stack pops decrement its value by 1. Upon any reset and power-on, the value 7 is stored in the Stack Pointer, which means that the space of RAM reserved for the stack starts at this location. If another value is written to this register, the entire Stack is moved to the new memory location. P0, P1, P2, P3 - Input/Output Registers

If neither external memory nor serial communication system are used then 4 ports with in total of 32 input/output pins are available for connection to peripheral environment. Each bit within these ports affects the state and performance of appropriate pin of the microcontroller. Thus, bit logic state is reflected on appropriate pin as a voltage (0 or 5 V) and vice versa, voltage on a pin reflects the state of appropriate port bit. As mentioned, port bit state affects performance of port pins, i.e. whether they will be configured as inputs or outputs. If a bit is cleared (0), the appropriate pin will be configured as an output, while if it is set (1), the appropriate pin will be configured as an input. Upon reset and power-on, all port bits are set (1), which means that all appropriate pins will be configured as inputs.

I/O ports are directly connected to the microcontroller pins. Accordingly, logic state of these registers can be checked by voltmeter and vice versa, voltage on the pins can be checked by inspecting their bits!

2.6 Counters and Timers


As you already know, the microcontroller oscillator uses quartz crystal for its operation. As the frequency of this oscillator is precisely defined and very stable, pulses it generates are always of the same width, which makes them ideal for time measurement. Such crystals are also used in quartz watches. In order to measure time between two events it is sufficient to count up pulses coming from this oscillator. That is exactly what the timer does. If the timer is properly programmed, the value stored in its register will be incremented (or decremented) with each coming pulse, i.e. once per each machine cycle. A single machine-cycle instruction lasts for 12 quartz oscillator periods, which means that by embedding quartz with oscillator frequency of 12MHz, a number stored in the timer register will be changed million times per second, i.e. each microsecond. The 8051 microcontroller has 2 timers/counters called T0 and T1. As their names suggest, their main purpose is to measure time and count external events. Besides, they can be used for generating clock pulses to be used in serial communication, so called Baud Rate.

Timer T0 As seen in figure below, the timer T0 consists of two registers TH0 and TL0 representing a low and a high byte of one 16-digit binary number.

Accordingly, if the content of the timer T0 is equal to 0 (T0=0) then both registers it consists of will contain 0. If the timer contains for example number 1000 (decimal), then the TH0 register (high byte) will contain the number 3, while the TL0 register (low byte) will contain decimal number 232.

Formula used to calculate values in these two registers is very simple: TH0 256 + TL0 = T Matching the previous example it would be as follows: 3 256 + 232 = 1000

Since the timer T0 is virtually 16-bit register, the largest value it can store is 65 535. In case of exceeding this value, the timer will be automatically cleared and counting starts from 0. This condition is called an overflow. Two registers TMOD and TCON are closely connected to this timer and control its operation. TMOD Register (Timer Mode) The TMOD register selects the operational mode of the timers T0 and T1. As seen in figure below, the low 4 bits (bit0 - bit3) refer to the timer 0, while the high 4 bits (bit4 - bit7) refer to the timer 1. There are 4 operational modes and each of them is described herein.

Bits of this register have the following function:

GATE1 enables and disables Timer 1 by means of a signal brought to the INT1 pin (P3.3): 1 - Timer 1 operates only if the INT1 bit is set. 0 - Timer 1 operates regardless of the logic state of the INT1 bit. C/T1 selects pulses to be counted up by the timer/counter 1: 1 - Timer counts pulses brought to the T1 pin (P3.5). 0 - Timer counts pulses from internal oscillator. T1M1,T1M0 These two bits select the operational mode of the Timer 1. T1M0 0 1 0 1 Mode 0 1 2 3 Description 13-bit timer 16-bit timer 8-bit autoreload Split mode 0 0 1 1

T1M1

GATE0 enables and disables Timer 1 using a signal brought to the INT0 pin (P3.2): 1 - Timer 0 operates only if the INT0 bit is set. 0 - Timer 0 operates regardless of the logic state of the INT0 bit. C/T0 selects pulses to be counted up by the timer/counter 0:

1 - Timer counts pulses brought to the T0 pin (P3.4). 0 - Timer counts pulses from internal oscillator. T0M1,T0M0 These two bits select the oprtaional mode of the Timer 0.

T0M1 0 0 1 1

T0M0 0 1 0 1

Mode 0 1 2 3

Description 13-bit timer 16-bit timer 8-bit autoreload Split mode

Timer 0 in mode 0 (13-bit timer) This is one of the rarities being kept only for the purpose of compatibility with the previuos versions of microcontrollers. This mode configures timer 0 as a 13bit timer which consists of all 8 bits of TH0 and the lower 5 bits of TL0. As a result, the Timer 0 uses only 13 of 16 bits. How does it operate? Each coming pulse causes the lower register bits to change their states. After receiving 32 pulses, this register is loaded and automatically cleared, while the higher byte (TH0) is incremented by 1. This process is repeated until registers count up 8192 pulses. After that, both registers are cleared and counting starts from 0. Timer 0 in mode 2 (Auto-Reload Timer) Mode 2 configures timer 0 as an 8-bit timer. Actually, timer 0 uses only one 8bit register for counting and never counts from 0, but from an arbitrary value (0-255) stored in another (TH0) register. The following example shows the advantages of this mode. Suppose it is necessary to constantly count up 55 pulses generated by the clock. If mode 1 or mode 0 is used, It is necessary to write the number 200 to the timer registers and constantly check whether an overflow has occured, i.e. whether they reached the value 255. When it happens, it is necessary to rewrite the number 200 and repeat the whole procedure. The same procedure is automatically performed by the microcontroller if set in mode 2. In fact, only the TL0 register operates as a timer, while another (TH0) register stores the value from which the counting starts. When the TL0 register is loaded, instead of being cleared, the contents of TH0 will be reloaded to it. Referring to the previous example, in order to register each 55th pulse, the best solution

is to write the number 200 to the TH0 register and configure the timer to operate in mode 2. Timer 0 in Mode 3 (Split Timer) Mode 3 configures timer 0 so that registers TL0 and TH0 operate as separate 8bit timers. In other words, the 16-bit timer consisting of two registers TH0 and TL0 is split into two independent 8-bit timers. This mode is provided for applications requiring an additional 8-bit timer or counter. The TL0 timer turns into timer 0, while the TH0 timer turns into timer 1. In addition, all the control bits of 16-bit Timer 1 (consisting of the TH1 and TL1 register), now control the 8-bit Timer 1. Even though the 16-bit Timer 1 can still be configured to operate in any of modes (mode 1, 2 or 3), it is no longer possible to disable it as there is no control bit to do it. Thus, its operation is restricted when timer 0 is in mode 3 imer Control (TCON) Register TCON register is also one of the registers whose bits are directly in control of timer operation. Only 4 bits of this register are used for this purpose, while rest of them is used for interrupt control to be discussed later.

TF1 bit is automatically set on the Timer 1 overflow. TR1 bit enables the Timer 1. 1 - Timer 1 is enabled. 0 - Timer 1 is disabled. TF0 bit is automatically set on the Timer 0 overflow. TR0 bit enables the timer 0. 1 - Timer 0 is enabled. 0 - Timer 0 is disabled.

2.7 UART (Universal Asynchronous Receiver and Transmitter)


One of the microcontroller features making it so powerful is an integrated UART, better known as a serial port. It is a full-duplex port, thus being able to transmit and receive data simultaneously and at different baud rates. Without it, serial data send and receive would be an enormously complicated part of the program in which the pin state is constantly changed and checked at

regular intervals. When using UART, all the programmer has to do is to simply select serial port mode and baud rate. When it's done, serial data transmit is nothing but writing to the SBUF register, while data receive represents reading the same register. The microcontroller takes care of not making any error during data transmission.

Serial port must be configured prior to being used. In other words, it is necessary to determine how many bits is contained in one serial word, baud rate and synchronization clock source. The whole process is in control of the bits of the SCON register (Serial Control). Serial Port Control (SCON) Register

SM0 - Serial port mode bit 0 is used for serial port mode selection. SM1 - Serial port mode bit 1. SM2 - Serial port mode 2 bit, also known as multiprocessor communication enable bit. When set, it enables multiprocessor communication in mode 2 and 3, and eventually mode 1. It should be cleared in mode 0. REN - Reception Enable bit enables serial reception when set. When cleared, serial reception is disabled. TB8 - Transmitter bit 8. Since all registers are 8-bit wide, this bit solves the problem of transmiting the 9th bit in modes 2 and 3. It is set to transmit a logic 1 in the 9th bit. RB8 - Receiver bit 8 or the 9th bit received in modes 2 and 3. Cleared by hardware if 9th bit received is a logic 0. Set by hardware if 9th bit received is a logic 1. TI - Transmit Interrupt flag is automatically set at the moment the last bit of one byte is sent. It's a signal to the processor that the line is available for a new byte transmite. It must be cleared from within the software.

RI - Receive Interrupt flag is automatically set upon one byte receive. It signals that byte is received and should be read quickly prior to being replaced by a new data. This bit is also cleared from within the software.

As seen, serial port mode is selected by combining the SM0 and SM2 bits: SM0 0 0 1 1 SM1 0 1 0 1 Mode 0 1 2 3 Description 8-bit Shift Register 8-bit UART 9-bit UART 9-bit UART Baud Rate 1/12 the quartz frequency Determined by the timer 1 1/32 the quartz frequency (1/64 the quartz frequency) Determined by the timer 1

8051 Microcontroller Interrupts


There are five interrupt sources for the 8051, which means that they can recognize 5 different events that can interrupt regular program execution. Each interrupt can be enabled or disabled by setting bits of the IE register. Likewise, the whole interrupt system can be disabled by clearing the EA bit of the same register. Refer to figure below. Now, it is necessary to explain a few details referring to external interruptsINT0 and INT1. If the IT0 and IT1 bits of the TCON register are set, an interrupt will be generated on high to low transition, i.e. on the falling pulse edge (only in that moment). If these bits are cleared, an interrupt will be continuously executed as far as the pins are held low. IE Register (Interrupt Enable)

EA - global interrupt enable/disable: 0 - disables all interrupt requests. 1 - enables all individual interrupt requests. ES - enables or disables serial interrupt:

0 - UART system cannot generate an interrupt. 1 - UART system enables an interrupt. ET1 - bit enables or disables Timer 1 interrupt: 0 - Timer 1 cannot generate an interrupt. 1 - Timer 1 enables an interrupt. EX1 - bit enables or disables external 1 interrupt: 0 - change of the pin INT0 logic state cannot generate an interrupt. 1 - enables an external interrupt on the pin INT0 state change. ET0 - bit enables or disables timer 0 interrupt: 0 - Timer 0 cannot generate an interrupt. 1 - enables timer 0 interrupt. EX0 - bit enables or disables external 0 interrupt: 0 - change of the INT1 pin logic state cannot generate an interrupt. 1 - enables an external interrupt on the pin INT1 state change. Interrupt Priorities

It is not possible to forseen when an interrupt request will arrive. If several interrupts are enabled, it may happen that while one of them is in progress, another one is requested. In order that the microcontroller knows whether to continue operation or meet a new interrupt request, there is a priority list instructing it what to do. The priority list offers 3 levels of interrupt priority: 1. Reset! The apsolute master. When a reset request arrives, everything is stopped and the microcontroller restarts. 2. Interrupt priority 1 can be disabled by Reset only. 3. Interrupt priority 0 can be disabled by both Reset and interrupt priority 1. The IP Register (Interrupt Priority Register) specifies which one of existing interrupt sources have higher and which one has lower priority. Interrupt priority is usually specified at the beginning of the program. According to that, there are several possibilities:

If an interrupt of higher priority arrives while an interrupt is in progress, it will be immediately stopped and the higher priority interrupt will be executed first. If two interrupt requests, at different priority levels, arrive at the same time then the higher priority interrupt is serviced first.

If the both interrupt requests, at the same priority level, occur one after another, the one which came later has to wait until routine being in progress ends. If two interrupt requests of equal priority arrive at the same time then the interrupt to be serviced is selected according to the following priority list: 1. External interrupt INT0 2. Timer 0 interrupt 3. External Interrupt INT1 4. Timer 1 interrupt 5. Serial Communication Interrupt IP Register (Interrupt Priority)

The IP register bits specify the priority level of each interrupt (high or low priority).

PS - Serial Port Interrupt priority bit Priority 0 Priority 1 PT1 - Timer 1 interrupt priority Priority 0 Priority 1 PX1 - External Interrupt INT1 priority Priority 0 Priority 1 PT0 - Timer 0 Interrupt Priority Priority 0 Priority 1 PX0 - External Interrupt INT0 Priority Priority 0 Priority 1

2.9 8051 Microcontroller Power Consumption Control


Generally speaking, the microcontroller is inactive for the most part and just waits for some external signal in order to takes its role in a show. This can cause some problems in case batteries are used for power supply. In extreme

cases, the only solution is to set the whole electronics in sleep mode in order to minimize consumption. A typical example is a TV remote controller: it can be out of use for months but when used again it takes less than a second to send a command to TV receiver. The AT89S53 uses approximately 25mA for regular operation, which doesn't make it a pover-saving microcontroller. Anyway, it doesnt have to be always like that, it can easily switch the operating mode in order to reduce its total consumption to approximately 40uA. Actually, there are two power-saving modes of operation: Idle and Power Down. Power Down mode By setting the PD bit of the PCON register from within the program, the microcontroller is set to Power down mode, thus turning off its internal oscillator and reduces power consumption enormously. The microcontroller can operate using only 2V power supply in power- down mode, while a total power consumption is less than 40uA. The only way to get the microcontroller back to normal mode is by reset. While the microcontroller is in Power Down mode, the state of all SFR registers and I/O ports remains unchanged. By setting it back into the normal mode, the contents of the SFR register is lost, but the content of internal RAM is saved. Reset signal must be long enough, approximately 10mS, to enable stable operation of the quartz oscillator. PCON register

The purpose of the Register PCON bits is:


SMOD Baud rate is twice as much higher by setting this bit. GF1 General-purpose bit (available for use). GF1 General-purpose bit (available for use). GF0 General-purpose bit (available for use). PD By setting this bit the microcontroller enters the Power Down mode. IDL By setting this bit the microcontroller enters the Idle mode.

Previous Chapter | Table of Contents | Next Chapter

LED displays

Basically, an LED display is nothing more than several LEDs moulded in the same plastic case. There are many types of displays composed of several dozens of built in diodes which can display different symbols.

Most commonly used is a so called 7-segment display. It is composed of 8 LEDs, 7 segments are arranged as a rectangle for symbol displaying and there is an additional segment for decimal point displaying. In order to simplify connecting, anodes and catodes of all diodes are connected to the common pin so that there are common anode displays and common catode displays, respectively. Segments are marked with the latters from A to G, plus dp, as shown in the figure on the left. On connecting, each diode is treated separtely, which means that each must have its own current limiting resistor. Displays connected to the microcontroller usually occupy a large number of valuable I/O pins, which can be a big problem especially if it is needed to display multy digit numbers. The problem is more than obvious if, for example, it is needed to display two 6-digit numbers (a simple calculation shows that 96 output pins are needed in this case). The solution to this problem is called MULTIPLEXING. This is how an optical illusion based on the same operating principle as a film camera is made. Only one digit is active at a time, but they change their state so quickly making impression that all digits of a number are simultaneously active.

Here is an explanation on the figure above. First a byte representing units is applied on a microcontroller port and a transistor T1 is activated at the same time. After a while, the transistor T1 is turned off, a byte representing tens is applied on a port and a transistor T2 is activated. This process is being cyclically repeated at high speed for all digits and corresponding transistors. The fact that the microcontroller is just a kind of miniature computer designed to understand only the language of zeros and ones is fully expressed when displaying any digit. Namely, the microcontroller doesn't know what units, tens or hundreds are, nor what ten digits we are used to look like. Therefore, each number to be displayed must be prepared in the following way: First of all, a multy digit number must be split into units, tens etc. in a particular subroutine. Then each of these digits must be stored in special bytes. Digits get familiar format by performing masking. In other words, a

binary format of each digit is replaced by a different combination of bits in a simple subroutine. For example, the digit 8 (0000 1000) is replaced by the binary number 0111 111 in order to activate all LEDs displaying digit 8. The only diode remaining inactive in this case is reserved for the decimal point. If a microcontroller port is connected to the display in such a way that bit 0 activates segment a, bit 1 activates segment b, bit 2 segment c etc., then the table below shows the mask for each digit.

Digits to display dp 0 1 a 0 b 0

Display Segments c 0 d 0 e 0 f 0 g 1

1 2 3 4 5 6 7 8 9

1 1 1 1 1 1 1 1 1

0 0 0 1 0 0 0 0 0

0 0 0 0 1 1 0 0 0

1 1 0 0 0 0 0 0 0

1 0 0 1 0 0 1 0 0

1 0 1 1 1 0 1 0 1

1 1 1 0 0 0 1 0 0

1 0 0 0 0 0 1 0 0

In addition to digits from 0 to 9, some letters of alphabet - A, C, E, J, F, U, H, L, b, c, d, o, r, t - can also be displayed by performing appropriate masking. If the event that common chatode displays are used all units in the table should be replaced by zeros and vice versa. Additionally, NPN transistors should be used as drivers as well.

I/O port pins and their functions The four ports PO, Pi, P2, and P3 each use 8 pins, making them 8-bit ports. All the ports upon RESET are configured as inputs, ready to be used as input ports. When the first 0 is written to a port, it becomes an output. To reconfigure it as an input, a 1 must be sent to the port. To use any of these ports as an input port, it must be programmed, as we will explain throughout this section. First, we describe each port.

Port 0 Port 0 occupies a total of 8 pins (pins 32 -39). It can be used for input or output. To use the pins of port 0 as both input and output ports, each pin must be connected externally to a lOK-ohm pull-up resistor. This is due to the fact that PO is an open drain, unlike PI, P2, and P3, as Figure 4-2. Port 0 with Pull-Up Resistors we will soon see. Open drain is a term used for MOS chips in the same way that open collector is used for TTL chips. In any system using the 8051/52 chip, we normally connect PO to pull-up resistors. See Figure 4-2. In this way we take advantage of port 0 for both input and output. For example, the following code will continuously send out to port 0 the alternating values of 55H and AAH.

It must be noted that complementing 55H (01010101) turns it into AAH (10101010). By sending 55H and AAH to a given port continuously, we toggle all the bits of that port. Port 0 as input With resistors connected to port 0, in order to make it an input, the port must be programmed by writing 1 to all the bits. In the following code,

port 0 is configured first as an input port by writing Is to it, and then data is received from that port and sent to P1.

Dual role of port 0 As shown in Figure 4-1, port 0 is also designated as ADO - AD7, allowing it to be used for both address and data. When connecting an 8051/31 to an external memory, port 0 provides both address and data. The 8051 multiplexes address and data through port 0 to save pins. We discuss that in Chapter 14. Port 1 Port 1 occupies a total of 8 pins (pins 1 through 8). It can be used as input or output. In contrast to port 0, this port does not need any pull-up resistors since it already has pull-up resistors internally. Upon reset, port 1 is configured as an input port. The following code will continuously send out to port 1 the alternating values 55H and AAH.

Port 1 as input If port 1 has been configured as an output port, to make it an input port again, it must programmed as such by writing 1 to all its bits. The reason for this is discussed in

Appendix C.2. In the following code, port 1 is configured first as an input port by writing Is to it, then data is received from that port and saved in R7, R6, and R5.

Port 2 Port 2 occupies a total of 8 pins (pins 21 through 28). It can be used as input or output. Just like PI, port 2 does not need any pull-up resistors since it already has pull-up resistors internally. Upon reset, port 2 is configured as an input port. The following code will send out continuously to port 2 the alternating values 55H and AAH. That is, all the bits of P2 toggle continuously.

Port 2 as input To make port 2 an input, it must programmed as such by writing 1 to all its bits. In the following code, port 2 is configured first as an input port by writing 1 s to it. Then data is received from that port and is sent to PI continuously.

Dual role of port 2 In many systems based on the 8051, P2 is used as simple I/O. However, in 8031-based systems, port 2 must be used along with PO to provide the 16-bit address for external memory. As shown in Figure 4-1, port 2 is also designated as A8 - A15, indicating its dual function. Since an 8051/31 is capable of accessing 64K bytes of external memory, it needs a path for the 16 bits of the address. While PO provides the lower 8 bits via AO - A7, it is the job of P2 to provide bits A8 -A15 of the address. In other words, when the 8051/31 is connected to external memory, P2 is used for the upper 8 bits of the 16-bit address, and it cannot be used for I/O. This is discussed in detail in Chapter 14. From the discussion so far, we conclude that in systems based on 8751, 89C51, or DS589C4xO microcontrollers, we have three ports, PO, PI, and P2, for I/O operations. This should be enough for most microcontroller applications.

Light-emitting diode (LED)


Light-emitting diodes are elements for light signalization in electronics. They are manufactured in different shapes, colors and sizes. For their low price, low power consumption and simple use, they have almost completely pushed aside other light sources, bulbs at first place. They perform similar to common diodes with the difference that they emit light when current flows through them. Figure 1 shows how to interface the LED to microcontroller. As you can see the Anode is connected through a resistor to Vcc & the Cathode is connected to the Microcontroller pin. So when the Port Pin is HIGH the LED is OFF& when the Port Pin is LOW the LED is turned ON.

Flashing LED ALGORITHM


1. 2. 3. Start. Turn ON LED. Turn OFF LED.

4.

GO TO 2.

We now want to flash a LED. It works by turning ON a LED & then turning it OFF & then looping back to START. However the operating speed of microcontroller is very high so the flashing frequency will also be very fast to be detected by human eye.

Modified Flashing LED ALGORITHM


1. 2. 3. 4. 5. 6. Start. Turn ON LED. Wait for some time (delay). Turn OFF LED. Wait for some time (delay). Go To 2.

You can see in the modified algorithm that after turning ON the LED the controller waits for the delay period & then turns OFF the led & again waits for the delay period & then goes back to the start. 1. 2. 3. 4. 5. 6. 7. ORG 0000h. loop: CLR P2.0 CALL DELAY SETB P2.0 CALL DELAY JMP loop

In the above program LED is connected to P2.0. Seg displays are are basically 7 LED's. It will be much easier to understand if you first read Interfacing LED's to

Microcontroller.

Basically there are two types of 7-Seg display's: Common Cathode where all the segments share the same Cathode. Common Anode where all Segments share the same Anode.

Here we will be only discussing the Common Anode type.In common Anode in order to turn ON a segment the corresponding pin must be set to 0. And to turn it OFF it is set to 1.

Switches and Pushbuttons


There is nothing simpler than this! This is the simplest way of controlling appearance of some voltage on microcontrollers input pin. There is also no need for additional explanation of how these components operate.

Nevertheless, it is not so simple in practice... This is about something commonly unnoticeable when using these components in everyday life. It is about contact bounce- a common problem with m e c h a n i c a l switches. If contact switching does not happen so quickly, several consecutive bounces can be noticed prior to maintain stable state. The reasons for this are: vibrations, slight rough spots and dirt. Anyway, whole this process does not last long (a few micro- or miliseconds), but long enough to be registered by the microcontroller. Concerning pulse counter, error occurs in almost 100% of

cases!

The simplest solution is to connect simple RC circuit which will suppress each quick voltage change. Since the bouncing time is not defined, the values of elements are not strictly determined. In the most cases, the values shown on figure are sufficient. If complete safety is needed, radical measures should be taken! The circuit, shown on the figure (RS flip-flop), changes logic state on its output with the first pulse triggered by contact bounce. Even though this is more expensive solution (SPDT switch), the problem is definitely resolved! Besides, since the condensator is not used, very short pulses can be also registered in this way.

In addition to these hardware solutions, a simple software solution is commonly applied too: when a program tests the state of some input pin and finds changes, the check should be done one more time after certain time delay. If the change is confirmed it means that switch (or pushbutton) has changed its position. The advantages of such solution are obvious: it is free of charge, effects of disturbances are eliminated too and it can be adjusted to the worstquality contacts. Disadvantage is the same as in case of using RC filter-pulses shorter than program delay cannot be registered.

In 8051 PORT 1, PORT 2 & PORT 3 have internal 10k Pull-up resistors whereas this Pull-up resistor is absent in PORT 0. Hence PORT 1, 2 & 3 can be directly used to interface a switch whereas we have to use an external 10k pull-up resistor for PORT 0 to be used for switch interfacing or for any other input. Figure 1 shows switch interfacing for PORT 1, 2 & 3. Figure 2 shows switch interfacing to PORT 0.

For any pin to be used as an INPUT PIN a HIGH (1) should be written to the pin if you dont do this the pin will always be read as LOW.In the above figure when the switch is not pressed the 10k resistor provides the current needed for LOGIC 1 closure of switch provides LOGIC 0 to the controller PIN.Let's write a small program where whenever a switch is pressed a LED is turned ON. Consider that switch is connected to P2.0 & an LED connected to P2.1. PROGRAM 1 ORG 0000h SETB P2.0 SETB P2.1 loop1: JB P2.0,loop1

clr P2.1 loop2: JNB P2.0,loop2 SETB P2.1 AJMP loop1 First we initialize the Port Pins that we are using. Since we are using P2.0 as an Input Pin we write logic 1 to it (SETB P2.0). We are using PIN P2.1 for LED. Initially LED is turned OFF this is done by pulling the PIN HIGH (check LED interfacing Section). Now we check if the Switch is pressed or not. So we wait till switch is pressed (loop1: JB P2.0,loop1) as soon as switch is pressed the LED is TURNED ON ( CLR P2.1 ) . Then we wait till the switch to be released (loop2: JNB P2.0, loop2 ) & then we TURN OFF the LED (SETB P2.1). You must have noticed in the above program that the status of the input pin is same as that of Output Pin i.e. if the switch is not PRESSED (HIGH) the Output pin is also HIGH (LED OFF) & when the switch is PRESSED (LOW) the Output pin is also LOW (LED ON) using this logic we can write in another way. PROGRAM 2 ORG 0000h SETB P2.1 SETB P2.0 loop: MOV C,P2.0 MOV P2.1,C AJMP loop The Output of both the programs will be the same.Now you know the basic concept of switch interfacing. There is a problem in practically interfacing these switches to the controller. In the above case you have considered the switches to be an IDEAL SWITCH where when the switch is pressed the controller directly gets LOGIC 0. But practically when a switch is closed the contacts open & close rapidly for about 30ms. This is called as SWITCH BOUNCING. Figure 3 shows its waveform.

Figure 3

As you can see the switch release is clean without any bouncing. When a switch is pressed the contacts open & close for about 20ms. In the above programs the LED will flicker initially when the switch is pressed because of the SWITCH BOUNCING but since the flickering will be very fast & will not be detected by human eye.Even though 20ms is very short time in human terms for a microcontroller it is a very long time. Without SWITCH DEBOUNCING the controller will think that the switch was pressed many times.Let us modify PROGRAM 1 & used SWITCH DEBOUNCING in it.

Switch Interfacing & Debouncing


Over here we consider ONE Switch & TWO LED connected to a microcontroller. Please check the SWITCH INTERFACING and the LED INTERFACINGarticle to see how to connect Switches & LEDs to a microcontroller. Here is a program that will TURN ON A LED1 if a switch is debounced properly & will TOGGLE LED2 if there is some error in switch debouncing. LED1 will be ON until the switch is pressed & will turn OFF as soon as its released. We have taken the debounce period as 20ms. So once a LOW signal has been received from the switch the controller will again check the switch status after 20ms & if at that time the switch is high LED2 will be toggled and if the switch is LOW LED1 will be turned ON.

2.4 Memory Organization


The 8051 has two types of memory and these are Program Memory and Data Memory. Program Memory (ROM) is used to permanently save the program being executed, while Data Memory (RAM) is used for temporarily storing data and intermediate results created and used during the operation of the microcontroller. Depending on the model in use (we are still talking about the 8051 microcontroller family in general) at most a few Kb of ROM and 128 or 256 bytes of RAM is used. However All 8051 microcontrollers have a 16-bit addressing bus and are capable of addressing 64 kb memory. It is neither a mistake nor a big ambition of engineers who were working on basic core development. It is a matter of smart memory organization which makes these microcontrollers a real programmers goody.

Data Memory As already mentioned, Data Memory is used for temporarily storing data and intermediate results created and used during the operation of the microcontroller. Besides, RAM memory built in the 8051 family includes many registers such as hardware counters and timers, input/output ports, serial data buffers etc. The previous models had 256 RAM locations, while for the later models this number was incremented by additional 128 registers. However, the first 256 memory locations (addresses 0-FFh) are the heart of memory common to all the models belonging to the 8051 family. Locations available to the user occupy memory space with addresses 0-7Fh, i.e. first 128 registers. This part of RAM is divided in several blocks. The first block consists of 4 banks each including 8 registers denoted by R0-R7. Prior to accessing any of these registers, it is necessary to select the bank containing it. The next memory block (address 20h-2Fh) is bit- addressable, which means that each bit has its own address (0-7Fh). Since there are 16 such registers, this block contains in total of 128 bits with separate addresses (address of bit 0 of the 20h byte is 0, while address of bit 7 of the 2Fh byte is 7Fh). The third group of registers occupy addresses 2Fh-7Fh, i.e. 80 locations, and does not have any special functions or features

Memory expansion In case memory (RAM or ROM) built in the microcontroller is not sufficient, it is possible to add two external memory chips with capacity of 64Kb each. P2 and P3 I/O ports are used for their addressing and data transmission.

A Register (Accumulator)

A register is a general-purpose register used for storing intermediate results obtained during operation. Prior to executing an instruction upon any number or operand it is necessary to store it in the accumulator first. All results obtained from arithmetical operations performed by the ALU are stored in the accumulator. Data to be moved from one register to another must go through the accumulator. In other words, the A register is the most commonly used register and it is impossible to imagine a microcontroller without it. More than half instructions used by the 8051 microcontroller use somehow the accumulator. B Register Multiplication and division can be performed only upon numbers stored in the A and B registers. All other instructions in the program can use this register as a spare accumulator (A).

During the process of writing a program, each register is called by its name so that their exact addresses are not of importance for the user. During compilation, their names will be automatically replaced by appropriate addresses. R Registers (R0-R7)

This is a common name for 8 general-purpose registers (R0, R1, R2 ...R7). Even though they are not true SFRs, they deserve to be discussed here because of their purpose. They occupy 4 banks within RAM. Similar to the accumulator, they are used for temporary storing variables and intermediate results during operation. Which one of these banks is to be active depends on two bits of the PSW Register. Active bank is a bank the registers of which are currently used. The following example best illustrates the purpose of these registers. Suppose it is necessary to perform some arithmetical operations upon numbers previously stored in the R registers: (R1+R2) - (R3+R4). Obviously, a register for temporary storing results of addition is needed. This is how it looks in the program: MOV A,R3; Means: move number from R3 into accumulator ADD A,R4; Means: add number from R4 to accumulator (result remains in accumulator) MOV R5,A; Means: temporarily move the result from accumulator into R5 MOV A,R1; Means: move number from R1 to accumulator ADD A,R2; Means: add number from R2 to accumulator SUBB A,R5; Means: subtract number from R5 (there are R3+R4)

Program Status Word (PSW) Register

PSW register is one of the most important SFRs. It contains several status bits that reflect the current state of the CPU. Besides, this register contains Carry bit, Auxiliary Carry, two register bank select bits, Overflow flag, parity bit and user-definable status flag. P - Parity bit. If a number stored in the accumulator is even then this bit will be automatically set (1), otherwise it will be cleared (0). It is mainly used during data transmit and receive via serial communication. - Bit 1. This bit is intended to be used in the future versions of microcontrollers. OV Overflow occurs when the result of an arithmetical operation is larger than 255 and cannot be stored in one register. Overflow condition causes the OV bit to be set (1). Otherwise, it will be cleared (0). RS0, RS1 - Register bank select bits. These two bits are used to select one of four register banks of RAM. By setting and clearing these bits, registers R0-R7 are stored in one of four banks of RAM. RS1 0 0 1 1 RS2 0 1 0 1 Space in RAM Bank0 00h-07h Bank1 08h-0Fh Bank2 10h-17h Bank3 18h-1Fh

F0 - Flag 0. This is a general-purpose bit available for use. AC - Auxiliary Carry Flag is used for BCD operations only. CY - Carry Flag is the (ninth) auxiliary bit used for all arithmetical operations and shift instructions. Data Pointer Register (DPTR) DPTR register is not a true one because it doesn't physically exist. It consists of two separate registers: DPH (Data Pointer High) and (Data Pointer Low). For this reason it may be treated as a 16-bit register or as two independent 8-bit registers. Their 16 bits are primarly used for external memory addressing.

Besides, the DPTR Register is usually used for storing data and intermediate results.

Stack Pointer (SP) Register

A value stored in the Stack Pointer points to the first free stack address and permits stack availability. Stack pushes increment the value in the Stack Pointer by 1. Likewise, stack pops decrement its value by 1. Upon any reset and power-on, the value 7 is stored in the Stack Pointer, which means that the space of RAM reserved for the stack starts at this location. If another value is written to this register, the entire Stack is moved to the new memory location. P0, P1, P2, P3 - Input/Output Registers

If neither external memory nor serial communication system are used then 4 ports with in total of 32 input/output pins are available for connection to peripheral environment. Each bit within these ports affects the state and performance of appropriate pin of the microcontroller. Thus, bit logic state is reflected on appropriate pin as a voltage (0 or 5 V) and vice versa, voltage on a pin reflects the state of appropriate port bit. As mentioned, port bit state affects performance of port pins, i.e. whether they will be configured as inputs or outputs. If a bit is cleared (0), the appropriate pin will be configured as an output, while if it is set (1), the appropriate pin will be configured as an input. Upon reset and power-on, all port bits are set (1), which means that all appropriate pins will be configured as inputs.

I/O ports are directly connected to the microcontroller pins. Accordingly, logic state of these registers can be checked by voltmeter and vice versa, voltage on the pins can be checked by inspecting their bits!

You might also like