You are on page 1of 190

Embedded Systems with 8051 C

Part 1

8051 C INTRODUCTION

Ps Vs Cs
On the left is a block diagram of a general purpose microprocessor based computer like the PCs and the laptops all of us are familiar with [minus the output device (f.e. CRT display), the input device (f.e. keyboard) and the secondary storage (f.e. hard disk)] To the right is the block diagram of the same computer, implemented on a single chip of silicon. We call this one chip implementation of a computer, or computer-on-a-single-chip, a MICROCONTROLLER

Cs in Embedded Systems

The Intel 8051 C


In 1981, Intel came out with an 8-bit uC called 8051 This uC had 128 bytes of RAM, 4K (4096) bytes of on-chip ROM, 2 timers, 1 serial port, and 4 8bit wide I/O ports all on a single 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 8bit pieces to be processed by the CPU.

Although the 8051 can have a maximum of 64K bytes of on-chip ROM, many manufacturers have put only 4K bytes or 4096 bytes on the chip. 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.

Block Diagram of 8051 C

Features of Intel 8051 C

8052 C
8052 is an advanced 8051. The 8052 an extra 128 bytes of RAM and an extra timer. Therefore, 8052 has 256 bytes of RAM and 3 timers. It has 8K bytes of on-chip program ROM instead of 4K bytes.

AT89S8253 C from Atmel Corporation in Dual In-Line (DIP) Package

Same AT89S8253 C from Atmel Corporation in Quad Package

AT89S8253 from Atmel Corporation

COMMON REGISTERS OF THE 8051 uC


The most widely used registers of the 8051 uC are the A, B, R0, R1, R2, R3, R4, R5, R6, R7, DPTR and PC All these registers are 8-bits, except DPTR and the program counter which are 16 bit

8051
8-bit Registers or Byte Registers

16-bit Registers

THE A-REGISTER OR THE ACCUMULATOR REGISTER


REGISTER A IS CALLED ACCUMULATOR THE ACCUMULATOR IS AN 8-BITS WIDE REGISTER ACCUMULATOR IS USED FOR ALL ARITHMETIC AND LOGIC INSTRUCTIONS

Simple Instructions
MOV instruction
MOV destination, source copies source to destination MOV A,#55H MOV R0,A MOV R1,A MOV R2,A MOV R3,#95H MOV A,R3 ;load value 55H into reg A ;copy contents of A into R0 ;(A=R0=55H) ;copy contents of A into R1 ;(A=R0=R1=55H) ;copy contents of A into R2 ;(A=R0=R1=R2=55H) ;load value 95H into R3 (R3=95H) ;copy contents of R3 into A (A=R3=95H)

ADD instruction
ADD A, source ADD the source operand to the accumulator register
MOV A,#25H ;load 25H into A MOV R2,#34H ;load 34H into R2 ADD A,R2 ;add R2 to accumulator

Executing the program above results in A = 59H

ASSEMBLY PROGRAMMING
Structure of Assembly Language Code
ORG 0H MOV R5,#25H MOV R7,#34H MOV A,#0 ADD A,R5 ;start (origin) at 0 ;load 25H into R5 ;load 34H into R7 ;load 0 into A ;add contents of R5 to A ;now A = A + R5 ADD A,R7 ;add contents of R7 to A ;now A = A + R7 ADD A, #12H ;add to A value 12H ;now A = A + 12H HERE: SJMP HERE ;stay in this loop END ;end of asm source file

Sample Assembly Language Program

ASSEMBLING RUNNING AN PROGRAM

AND 8051

An Assembly language instruction consists of four fields:


[label : ] mnemonic [operands] [;comment]

ASSEMBLING RUNNING AN PROGRAM

AND 8051

Steps to Create a Program

PC & ROM SPACE IN 8051


Program counter in the 8051
16 bits wide can access program addresses 0000 to FFFFH total of 64K bytes of code

PC & ROM IN 8051


Where the 8051 wakes up when it is powered up:
wakes up at memory address 0000 when it is powered up first opcode must be stored at ROM address 0000H

PC & ROM IN 8051


Placing code in program ROM
the opcode and operand are placed in ROM locations starting at memory 0000

PC & ROM IN 8051


ROM memory map in the 8051 family

8051 On-Chip ROM Address Range

8051 DATA TYPES AND DIRECTIVES


8051 data type and directives
DB (define byte) ORG (origin) EQU (equate) END directive

8051 DATA TYPES AND DIRECTIVES


Rules for labels in Assembly language
each label name must be unique first character must be alphabetic reserved words must not be used as labels

8051 FLAG BITS AND THE PSW REGISTER


PSW (program status word) register

Bits of the PSW Register

8051 FLAG BITS AND THE PSW REGISTER

Instructions That Affect Flag Bits

8051 REGISTER BANKS AND STACK


RAM memory space allocation in the 8051

RAM Allocation in the 8051

8051 REGISTER BANKS AND STACK


Register banks in the 8051

8051 Register Banks and their RAM Addresses

8051 REGISTER BANKS AND STACK


How to switch register banks

PSW Bits Bank Selection

8051 REGISTER BANKS AND STACK


Stack in the 8051
section of RAM used to store information temporarily could be data or an address CPU needs this storage area since there are only a limited number of registers

Par t 2
8051 C DATA PROCESSING INSTRUCTIONS I
ARITHMETIC INSTRUCTIONS

Arithmetic Instructions
Add Subtract Increment Decrement Multiply Divide Decimal adjust

Arithmetic Instructions
Mnemonic ADD A, byte ADDC A, byte SUBB A, byte INC A INC byte INC DPTR DEC A DEC byte MUL AB DIV AB DA A Description add A to byte, put result in A add with carry subtract with borrow increment A increment byte in memory increment data pointer decrement accumulator decrement byte multiply accumulator by b register divide accumulator by b register decimal adjust the accumulator

ADD Instructions
add a, byte ; a a + byte addc a, byte ; a a + byte + C These instructions affect 3 bits in PSW: C = 1 if result of add is greater than FF AC = 1 if there is a carry out of bit 3 OV = 1 if there is a carry out of bit 7, but not from bit 6, or visa versa.

Instructions that Affect PSW bits

ADD Examples
mov a, #0x3F add a, #0xD3
0011 1111 1101 0011 0001 0010

What is the value of the C, AC, OV flags after the second instruction is executed?

C = 1 AC = 1 OV = 0

Signed Addition and Overflow 0111 1111 (positive 127)


2s 0000 0111 1000 1111 complement: 0000 00 0 1111 0000 1111
0111 0011 (positive 115) 1111 0010 (overflow cannot represent 242 in 8 bits 2s complement) 1000 1111 1101 0011 0110 0010 (negative 113) (negative 45) (overflow)

7F 127 80 -128 FF -1

0011 1111 (positive) 1101 0011 (negative) 0001 0010 (never overflows)

Addition Example for the Assembler


; Computes Z = X + Y; Adds values at locations 0x78 and 0x79 and puts them in location 0x7A $INCLUDE (C8051F020.inc) ; EQUATES ;----------------------------------------------------------------------------X equ 0x78 Y equ 0x79 Z equ 0x7A ; RESET and INTERRUPT VECTORS ;----------------------------------------------------------------------------cseg at 0 ljmp Main ; CODE SEGMENT ;----------------------------------------------------------------------------cseg at 100h Main: mov 0xFF, #0DEh ; Disable watchdog timer mov 0xFF, #0ADh mov a, X add a, Y mov Z, a nop end

Subtract
SUBB A, byte subtract with borrow

Example:
SUBB A, #0x4F ; A A 4F C

Notice that there is no subtraction WITHOUT borrow. Therefore, if a subtraction without borrow is desired, it is necessary to clear the C flag.

Increment and DecrementA INC A increment


INC byte INC DPTR DEC A DEC byte increment byte in memory increment data pointer decrement accumulator decrement byte

The increment and decrement instructions do NOT affect the C flag. Notice we can only INCREMENT the data pointer, not decrement.

Example: Increment 16-bit Word


Clearly we have to take the word in 2 8-bit long registers Assume 16-bit word in R3:R2
mov a, r2 add a, #1 mov r2, a mov a, r3 addc a, #0 mov r3, a ; use add rather than increment to affect C ; add C to most significant byte

Multiply
When multiplying two 8-bit numbers, the size of the maximum product is 16-bits FF x FF = FE01 (255 x 255 = 65025)
MUL AB ; BA A * B

Note: B gets the HIGH byte, A gets the LOW byte

Division
Integer Division
DIV AB ; divide A by B A Quotient(A/B), B Remainder(A/B) OV - used to indicate a divide by zero condition. C set to zero

Decimal Adjust
DA a ; decimal adjust a Used to facilitate BCD addition. Adds 6 to either high or low nibble after an addition to create a valid BCD number. Example:
mov a, mov b, add a, DA a #0x23 #0x29 b ; a 23 + 29 = 4C (wanted 52) ; a a + 6 = 52

Note: This instruction does NOT convert binary to BCD!

Par t 3
8051 C DATA PROCESSING INSTRUCTIONS II
LOGIC INSTRUCTIONS

Logic Bitwise logic operations (AND, OR, XOR, NOT) Instr uctions
Clear Rotate Swap

Logic instructions do NOT affect the flags in PSW

Bitwise Logic
Examples:

ANL AND ORL OR XRL eXclusive OR CPL Complement

00001111 ANL 10101100 00001100 00001111 ORL 10101100 10101111 00001111 XRL 10101100 10100011 CPL 10101100 01010011

Address Modes with Logic


ANL AND ORL OR XRL eXclusive oR

a, byte
direct, reg. indirect, reg, immediate

byte, a
direct

byte, #constant
CPL Complement

ex: cpl a

Uses of Logic Instructions


Force individual bits low, without affecting other bits.
anl PSW, #0xE7 anl PSW, #11100111b ;PSW AND 11100111 ; can use binary

Force individual bits high.


orl PSW, #0x18 ;PSW OR 00011000

Complement individual bits


xrl P1, #0x40 ;P1 XRL 01000000

Other Logic Instructions


CLR - clear RL rotate left RLC rotate left through Carry RR rotate right RRC rotate right through Carry SWAP swap accumulator nibbles

CLR Set all bits to 0


CLR A CLR byte CLR Ri CLR @Ri (direct mode) (register mode) (register indirect mode)

Rotate
Rotate instructions operate only on a rl a mov a, #0xF0 rl a ; a 11110000 ; a 11100001

Rotate through Carry


C

rrc a

mov a, #0A9h add a, #14h rrc a

; a A9 ; a BD (10111101), C0 ; a 01011110, C1

Swap
swap a

mov a, #72h swap a

; a 27h

Bit Logic Operations


Some logic operations can be used with single bit operands
ANL C, bit ORL C, bit CLR C CLR bit CPL C CPL bit SETB C SETB bit ANL C, /bit ORL C, /bit
bit can be any of the bit-addressable RAM locations or SFRs.

Rotate and Multiplication/Division


Note that a shift left is the same as multiplying by 2, shift right is divide by 2 mov clr rlc rlc rrc a, #3 ; C ; C a ; A a ; A a ; A A 00000011 (3) 0 00000110 (6) 00001100 (12) 00000110 (6)

Shift/Multiply Example
Program segment to multiply by 2 and add 1 clr rl inc c a a

;multiply by 2 ;and add one

Part 4
JUMP AND LOOP INSTRUCTIONS

LOOP AND JUMP INSTRUCTIONS


Repeating a sequence of instructions a certain number of times is called a loop. 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. In this instruction both the register decrement and the decision to jump arc combined into a single instruction. The registers can be any of R0 - R7. The counter can also be a RAM location

LOOP AND JUMP INSTRUCTIONS

LOOP AND JUMP INSTRUCTIONS


Looping in the 8051
Problem 1 In the 8051, looping action with the instruction "DJNZ Rx, rel address" is limited to _______ iterations. Answer : 256 Problem 2 If a conditional jump is not taken, what is the next instruction to be executed? Answer : the instruction following the jump

LOOP AND JUMP INSTRUCTIONS


SJMP to itself using $ sign
Problem 3 In calculating the target address for a jump, a displacement is added to the contents of register ___________ . Answer: PC Problem 3 The mnemonic SJMP stands for __________ and it is a ____ - byte instruction. Answer: short jump , 2

Loop inside a loop


What happens if we want to repeat an action more times than 256?
Write a program to (a) load the accumulator with the value 55H, and (b) complement the ACC 700 times. 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. MOV A,#55H ;A=55H NEXT: MOV R3,#10 ;R3=10, the outer loop count AGAIN: CPL A MOV R2,#70 ;complement ;R2=70, the inner loop count

LOOP AND JUMP INSTRUCTIONS


Other conditional jumps

Other conditional jumps


JZ (jump if A = 0)
In this instruction the content of register A is checked. If it is zero, it jumps to the target address. JZ instruction can be used only for register A. It can only check to see whether the accumulator is zero, and it does not apply to any other register. Don't have to perform an arithmetic instruction such as decrement to use the JZ instruction.

Other conditional jumps


JNZ (jump if A 0)
In this instruction the content of register A is checked. If it is not zero, it jumps to the target address.

Other conditional jumps


JNC Jump if no carry, jumps if CY = 0)
carry flag bit in the flag (PSW) register is used to make the decision whether to jump "JNC label", the processor looks at the carry flag to see if it is raised (CY = 1). if it is not, the CPU starts to fetch and execute instructions from the address of the label. if CY = 1, it will not jump but will execute the next instruction below JNC.

Other conditional jumps


JC Jump if carry, jumps if CY = 1)
if CY = l it jumps to the target address

JB (jump if bit is high) JNB (jump if bit is low)

LOOP AND JUMP INSTRUCTIONS


All conditional jumps are short jumps

Table 31 8051 Conditional Jump Instructions

Unconditional jump instructions


There are two unconditional jumps: LJMP (long jump) and SJMP (short jump).
LJMP is 3-byte instruction in which the first byte is the op-code, and the second and third bytes represent the 16-bit address of the target location. The 2-byte target address allows a jump to any memory loca-tion from 0000 to FFFFH.

Unconditional jump instructions


SJMP (short jump)
2-byte instruction, the first byte is the op-code and the second byte is the relative address of the target location. The relative address range of 00 FFH is divided into forward and backward jumps; that is, within -128 to +127 bytes of memory relative to the address of the current PC (program counter). If the jump is forward, the target address can be within a space of 127 bytes from the current PC. If the target address is backward, the target address can be within -128 bytes from the current PC.

Calculating the short jump address


Using the following list tile, verify the jump forward address calculation.
Line 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 PC Op-code 0000 ORG 0000 0000 7800 0002 7455 0004 6003 0006 08 0007 04 0008 04 0009 2477 000B 5005 000D 000E F8 000F F9 0010 FA 0011 FB 0012 2B 0013 50F2 0015 80FE 0017 END Mnemonic MOV R0, MOV A, JZ NEXT INC R0 AGAIN: INC A NEXT: JNC OVER E4 MOV R0, A MOV R1, A MOV R2, A MOV R3, A OVER: JNC AGAIN HERE: Operand #003 #55H0 INC A ADD A, CLR A #77h

ADD A, R3 SJMP HERE

Calculating the short jump address

Part 5
CALL INSTRUCTIONS

CALL INSTRUCTIONS
CALL 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. There are two instructions : LCALL (long call) and ACALL (absolute call). Deciding which one to use depends on the target address.

CALL INSTRUCTIONS
LCALL (long call)
3-byte instruction, the first byte is the op-code and the second and third bytes are used for the address of the target subroutine. 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.

CALL INSTRUCTIONS
LCALL (long call)

Figure 31 8051 Assembly Main Program That Calls Subroutines

CALL INSTRUCTIONS

Part 6
TIMING CALCULATIONS

TIME DELAY FOR VARIOUS 8051 CHIPS


Machine cycle for the 8051
The MCU takes a certain number of clock cycles to execute an instruction. These clock cycles are referred to as machine cycles. In the 8051 family, the length of the machine cycle depends on the frequency of the crystal oscillator. The frequency of the crystal connected to the 8051 family can vary from 4 MHz to 30 MHz. In the original 8051, one machine cycle lasts 12 oscillator periods. Therefore, to calculate the machine cycle for the 8051, we take 1/12 of the crystal frequency, then take its inverse.

TIME DELAY FOR VARIOUS 8051 CHIPS


Machine cycle for the 8051

Clocks per Machine Cycle (MC) for Various 8051 Versions

TIME DELAY FOR VARIOUS 8051 CHIPS


Delay calculation for other versions of 8051

Table 33

Comparison of 8051 and DS89C4x0 Machine Cycles

TIME DELAY FOR VARIOUS 8051 CHIPS

Par t 7
8051 I/O PORT PROGRAMMING

WHAT ARE I/O PORTS?


I/O Ports are basically the interfaces which connect the 8051 uC to external devices After basic connection, that is, after setting up the hardware connection, I/O ports can read, that is, receive data from those devices and can also write, that is, send data to them Inputs can be read/received from ports and outputs can be written/sent to the I/O ports by writing suitable programs for the 8051 uC.

This is a very useful function because the 8051 uC can then be used for monitoring real world processes as we see in digital instruments where different parameters like Pressure, Temperature, Speed of Rotation, etc can be acquired and displayed

This is also very useful because microcontrollers have data processing capability (though limited) which can be used for processing these signals through programs (which we write), and based on the result perform some control function by sending data to the device through the output ports or pins of the microcontroller.

So for example, we can use the input port/pin of the 8051 uC to keep reading the temperature of an oven, and when the temperature exceeds a certain value, we can use the output port/pin of the 8051 uC to either turn-off the switch of the oven automatically or to activate a sound alarm (for manual intervention) and to once again turn it on when the temperature falls below a specified value or to activate a sound alarm.

ANALOGY OF PORTS
We have got sea ports, air ports, bus ports (what are called bus terminals) and rail ports (railway stations) in a city. These ports are used for connecting the city with the rest of the world for bringing people and cargo inside the city (Input Port) They are also used for sending people and cargo outside the city (Output Port) Generally we do not see separate physical ports in cities for Input and Output Functions Now this analogy pretty much applies for the 8051 uC as well

4 I/O Ports in the 8051 are like the 4 railway stations of a big city Individual Pins are like Platforms of the Railway Station You got 8 platforms (pins) per I/O port in 8051!

8051 Pin Diagram

8051 I/O PORT You have got 4 I/O ports in the 8051 uC. They are PROGRAMMING
named as P0, P1, P2, and P3. You have to always keep in mind that each of these 4 ports have 8 pins each. Individual pins of these ports are named as P0.1, P0.2, P0.3, and so on (Port 0 Platform No.1, Port 0 Platform No.2, and so on) When you RESET the 8051 uC then all the ports of the 8051 are configured as input ports, and are ready to read data, that is, take data inside, that is, all stations and all platforms of the stations are ready for receiving incoming trains!

8051 I/O PORT PROGRAMMING


And how do you reset the 8051 uC?
This is done by holding the RST pin (pin no. 9 in the 8051 pin diagram) at Logic 1 for 2 consecutive machine cycles. In practice, it means that you apply the voltage level corresponding to Logic 1 (+5V) to the RST pin of the 8051 uC for a very short time interval corresponding to 2 machine cycles of the 8051 uC.

8051 I/O PORT PROGRAMMING


When you write the first 0 to a port, then that port becomes an output port and can be used for writing data or sending data outside. For reconfiguring (phir se configuring ya dobara se configuring) the port (which you have made output port) as an input port, you have to move 1 to that port. For using any of these 4 uC ports for data input or output, you have to write programs in Assembly or C language.

Port 0
You can use this port as either an input port or an output port. Before using port 0 as an input or an output port, you have to connect each pin of port 0 to 10 Kilo ohm resistors as shown in the diagram on next slide. This is because the port P0 has no internal resistors. The other ports P1, P2, and P3 have internal or builtin resistors on the 8051 chip itself. So external resistors should not be connected to the pins of P1, P2, and P3 ports.

8051 I/O PROGRAMMING


Port 0

Port 0 with External Resistors

Port 0 as input
After connecting 10Kohm external resistors to all pins of port 0, in the manner shown earlier, in order to make port 0 an input port, the port must be programmed by writing 1 to all its bits.

Dual role of port 0


Port 0 is also designated as AD0 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.

8051 I/O PROGRAMMING


Port 1 It can be used as input or output. This port does not need any resistors since it already has resistors internally. Upon reset, port I is configured as an input port.

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.

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

DELAY SUBROUTINE
. . MOV R0, #30H . . ORG 300H DELAY: NOP AGAIN: DJNZ R0, AGAIN RET END

Port 2 Port 2 occupies a total of 8 pins (pins 21 through 28). It can be used as input or output. Port 2 does not need any external resistors since it already has external resistors internally. Upon reset, port 2 is configured as an input port.

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 is to it.

Dual role of port 2


In 8031-based systems, port 2 must be used along with P0 to provide the 16-bit address for external memory. 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. P0 provides the lower 8 bits via AD0 - AD7 P2 provides bits A8 - A 15 of the address. 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.

Port 3
Port 3 can be used as input or output. P3 does not need any external resistors. Port 3 is configured as an input port upon reset. Port 3 has the additional function of providing some extremely important signals such as interrupts, serial I/O, timer/counter and read/write control for external memory.

Port 3

Port 3 Alternate Functions

Different ways of toggling the entire 8 bits

Different ways of toggling the entire 8 bits

Ports status upon reset

Reset Value of Some 8051 Ports

PROGRAMMING INDIVIDUAL I/O PINS BY BIT MANIPULATION


A powerful feature of 80511/0 ports is their capability to access individual bits of the port without altering the rest of the bits in that port. Of the four 8051 ports, we can access either the entire 8 bits or any single bit without altering the rest. "SETB X. Y" where X is the port number 0, 1, 2, or 3, and Y is the desired bit number from 0 to 7 for data bits DO to D7. "SETB P1.5" sets bit 5 of port 1 high.

The following code toggles bit P1.2 continuously.

I/O ports and bit-addressability

Single-Bit Addressability of Ports

I/O BIT MANIPULATION PROGRAMMING


I/O ports and bit-addressability

Table 44

Single-Bit Instructions

I/O BIT MANIPULATION PROGRAMMING


Checking an input bit

Instructions For Reading an Input Port

Reading a single bit into the carry flag

Reading input pins vs. port latch


Some instructions read the contents of a port, modify its value, and write it back. (READ-MODIFY-WRITE) F.E. ANL P1, A
Reads internal port latch & brings it to

CPU
Data is ANDed with contents of A Result is rewritten to port latch Port Pin Data = Port Latch

Instructions for reading input ports


To make any bit of any 8051 port an input port, we must write 1 (logic high) to that bit. After we configure the port bits as input, we can use only certain instructions in order to get the external data present at the pins into the CPU.

Pin & Latch


Port Pins
Current state of port pin

Reading from Port: Data is read directly from port pins in case the port is configured as input. Writing to Port: Writes to an internal register (called latch reg) which is reflected to pin if port is configured as output.

Latch
To write data on port Data will be reflected/moved to port pin if configured as o/p, and will have no effect incase of i/p.

Reading latch for output port

Instructions Reading a Latch (Read-Modify-Write)

Read-modify-write feature
The ports in the 8051 can be accessed by the read-modify-write technique.
(1) reading the port (2) modifying its value (3) writing to the port

Sample Programs
Toggle all bits of P0, P1, and P2 every sec assuming crystal frequency of 11.0592 MHz

Main thing here is the delay loop


50% & 66% duty cycle square waves on P1.0 Monitor P0.1 till it is high
When high, read data from port 1 Low to High Pulse on P0.2 when this happens

P2.3 represents oven condition


If high, oven is hot high to low pulse on P1.5 to activate buzzer

Sample Pr og r ams

60% duty cycle sq waveform SETB P1.3 LCALL DELAY LCALL DELAY CLR P1.3 LCALL DELAY SJMP BACK

Oven HERE JNB 2.3 HERE SETB P1.5 CLR P1.5 SJMP HERE

SWITCH STATUS SETB P1.7 AGAIN: JB P1.2 OVER MOV P2, #N SJMP AGAIN OVER: MOV P2, #Y SJMP AGAIN

SWITCH TO P0.1 CHECK SWITCH SWITCH =1 THEN HIGH TO LOW TO ACTIVATE SIREN ON P1.7 SETB P0.1 AGAIN: MOV C, P0.1 JNC AGAIN SETB P1.7 CLR P1.7 SJMP AGAIN

SWITCH TO P1.0 LED TO P2.7 SWITCH STATUS SEND TO LED SETB P1.7 AGAIN: MOV C, P1.0 MOV P2.7, C SJMP AGAIN

Instructions vs. Directives


Assembler Directives
Instructions for the ASSEMBLER NOT 8051 instructions

Examples:
;cseg stands for code segment cseg at 1000h ;address of next instruction 1000h GREEN_LED equ P1.6 is

;symbol for Port 1, bit 6

Assembler Directives
DATA
SP MY_VAL

Used to define a name for memory locations


DATA DATA 0x81 0x44 ;special function registers ;RAM location

Address

EQU Used to create symbols that can be used to represent registers, numbers, and addresses
LIMIT VALUE SERIAL COUNT MY_VAL EQU EQU EQU EQU EQU 2000 LIMIT 200 + 'A' SBUF R5 0x44

Registers, numbers, addresses

Data Transfer Instructions MOV dest, source dest source


MOV dest, source 6 basic types:
MOV MOV MOV a, byte byte, a Rn, byte

dest source

MOV direct, byte MOV @Rn, byte MOV DPTR, data16

;move byte to accumulator ;move accumulator to byte ;move byte to register of ;current bank ;move byte to internal RAM ;move byte to internal RAM ;with address contained in Rn ;move 16-bit data into data ;pointer

Other Data Transfer Instructions


Stack instructions
PUSH byte POP byte ;increment ;move byte ;move from ;decrement stack pointer, on stack stack to byte, stack pointer

Exchange instructions

XCH a, byte ;exchange accumulator and ;byte XCHD a, byte ;exchange low nibbles of ;accumulator and byte

Addressing Modes
Immediate Mode specify data by its value
mov a, a = mov a, a = mov a, a = mov a, a = #0 ;put 0 in the accumulator 00000000 #0x11 ; put 11hex in the accumulator 00010001 #11 ; put 11 decimal in accumulator 00001011 #77h ; put 77 hex in accumulator 01110111

Addressing Modes
Direct Mode specify data by its 8-bit address
mov a, 0x70 mov 0xD0, a ; copy contents of RAM at 70h to a ; put contents of a into PSW

Addressing Modes
Register Addressing either source or destination is one of R0-R7 mov R0, a mov a, R0

Addressing Modes
Register Indirect the address of the source or destination is specified in registers Uses registers R0 or R1 for 8-bit address:
mov mov mov ; 0xD0, #0 ; use register bank 0 r0, #0x3C @r0, #3 ; memory at 3C gets #3 M[3C] 3

Uses DPTR register for 16-bit addresses:


mov dptr, #0x9000 ; dptr 9000h mov a, @dptr ; a M[9000] Note that 9000 is an address in external memory

Exer cise: Use Re gister Indir ect to access upper RAM block

Addressing Modes
Register Indexed Mode source or destination address is the sum of the base address and the accumulator. Base address can be DPTR or PC mov dptr, #4000h mov a, #5 movc a, @a + dptr ;a M[4005]

Addressing Modes
Register Indexed Mode Base address can be DPTR or PC
Addr 1000 1002 1003 cseg at 0x1000h mov a, #5 movc a, @a + PC nop ;a M[1008]

PC

A and B Registers
A and B are accumulators for arithmetic instructions They can be accessed by direct mode as special function registers: B address 0F0h A address 0E0h - use ACC for direct mode

Address Modes
mov sp, #0x40 push 0x55 pop b ; ; ; ;

Stack-oriented data transfer another form of register direct addressing, but using SP
Initialize SP SP SP+1, M[SP] M[55] M[41] M[55] b M[55]

Note: can only specify RAM or SFRs (direct mode) to push or pop. Therefore, to push/pop the accumulator, must use acc, not a: push acc push a

Stacks
push pop stack pointer stack

Go do the stack exercise..

Address Modes
Exchange Instructions two way data transfer XCH a, 0x30 ; a M[30] XCH a, R0 ; a R0 XCH a, @R0 ; a M[R0] XCHD a[3..0] ; exchange a[7..4] a, R0 R0[7..4] R0[3..0] digit Only 4 bits exchanged

Address Modes

Bit-Oriented Data Transfer transfers between individual bits. SFRs with addresses ending in 0 or 8 are bit-addressable. (80, 88, 90, 98, etc) Carry flag (C) (bit 7 in the PSW) is used as a single-bit accumulator RAM bits in addresses 20-2F are bit addressable

Examples of bit transfers of special function register bits:


mov C, P0.0 ; C bit 0 of P0

Bit Addressable 20h 2Fh (16 locations X Memory


2F 7F 2E 2D 2C 2B 2A 29 28 27 26 25 24 23 22 21 0F 20 07 06 05 04 03 02 01 1A 10 08 00 78

8-bits = 128 bits)

Bit addressing: mov C, 1Ah or mov C, 23h.2

SFRs that are Bit Addressable SFRs with addresses


of multiples of 0 and 8 are bit addressable.
SFRs

Address B

Register SPI0CN ADC0CN ACC PCA0CN PSW T2CON SMB0CN IP P3 IE P2 SCON P1 TCON P0

0xF8 0xF0 0xE8 0xE0 0xD8 0xD0 0xC8 0xC0 0xB8 0xB0 0xA8 0xA0 0x98 0x90 0x88 0x80

Notice that all 4 parallel I/O ports are bit addressable.

Pink are implemented in enhanced C8051F020

8051 SERIAL PORT PROGRAMMING

BASICS OF SERIAL COMMUNICATION

Figure 1

Serial versus Parallel Data Transfer

BASICS OF SERIAL COMMUNICATION


serial communication uses single data line making it much cheaper enables two computers in different cities to communicate over the telephone byte of data must be converted to serial bits using a parallel-in-serialout register and transmitted over a single data line receiving end there must be a serial-in-parallel-out shift register if transferred on the telephone line, it must be converted to audio tones by modem for short distance the signal can be transferred using wire how PC keyboards transfer data to the motherboard

BASICS OF SERIAL COMMUNICATION


2 methods, asynchronous and synchronous synchronous method transfers a block of data (characters) at a time asynchronous method transfers a single byte at a time Uses special IC chips called UART (universal asynchronous receiver-transmitter) and USART (universal synchronous-asynchronous receivertransmitter) 8051 chip has a built-in UART

BASICS OF SERIAL COMMUNICATION

Figure 2

Simplex, Half-, and Full-Duplex Transfers

BASICS OF SERIAL COMMUNICATION


Half- and full-duplex transmission if the data can be transmitted and received, it is a duplex transmission simplex transmissions the computer only sends data duplex transmissions can be half or full duplex depends on whether or not the data transfer can be simultaneous If one way at a time, it is half duplex If can go both ways at the same time, it is full duplex full duplex requires two wire conductors for the data lines (in addition to the signal ground)

BASICS OF SERIAL COMMUNICATION


Asynchronous serial communication and data framing
data coming in 0s and 1s to make sense of the data sender and receiver agree on a set of rules Protocol
how the data is packed how many bits/character when the data begins and ends

BASICS OF SERIAL COMMUNICATION


Start and stop bits
asynchronous method, each character is placed between start and stop bits called framing start bit is always one bit stop bit can be one or two bits start bit is always a 0 (low) stop bit(s) is 1 (high) LSB is sent out first

SECTION 10.1: BASICS OF SERIAL COMMUNICATION

Figure 3

Framing ASCII A (41H)

BASICS OF SERIAL COMMUNICATION


in modern PCs one stop bit is standard when transferring a text file of ASCII characters using 1 stop bit there is total of 10 bits for each character 8 bits for the ASCII code (1 parity bit), 1 bit each for the start and stop bits for each 8-bit character there are an extra 2 bits, which gives 20% overhead

BASICS OF SERIAL COMMUNICATION


Data transfer rate
rate of data transfer bps (bits per second) widely used terminology for bps is baud rate baud and bps rates are not necessarily equal baud rate is defined as the number of signal changes per second

BASICS OF SERIAL COMMUNICATION


RS232 standards
most widely used serial I/O interfacing standard input and output voltage levels are not TTL compatible 1 bit is represented by -3 to -25 V 0 bit is +3 to +25 V -3 to +3 is undefined to connect RS232 to a microcontroller system must use voltage converters such as MAX232 to convert the TTL logic levels to the RS232 voltage levels, and vice versa MAX232 IC chips are commonly referred to as line drivers

BASICS OF SERIAL COMMUNICATION

Figure 5

DB-9 9-Pin Connector

Table 2

IBM PC DB-9 Signals

BASICS OF SERIAL COMMUNICATION


Data communication classification
DTE (data terminal equipment) DCE (data communication equipment) DTE - terminals and computers that send and receive data DCE - communication equipment responsible for transferring the data simplest connection between a PC and microcontroller requires a minimum of three pins, TxD, RxD, and ground

BASICS OF SERIAL COMMUNICATION

Figure 6

Null Modem Connection

BASICS OF SERIAL COMMUNICATION


Examining RS232 hand-shaking signals
many of the pins of the RS-232 connector are used for handshaking signals they are not supported by the 8051 UART chip

BASICS OF SERIAL COMMUNICATION


PC/compatible COM ports
PC/compatible computers (Pentium) microprocessors normally have two COM ports both ports have RS232-type connectors COM ports are designated as COM 1 and COM 2 can connect the 8051 serial port to the COM 2 port

8051 CONNECTION TO RS232


RxD and TxD pins in the 8051
8051 has two pins used for transferring and receiving data serially TxD and RxD are part of the port 3 group pin 11 (P3.1) is assigned to TxD pin 10 (P3.0) is designated as RxD these pins are TTL compatible require a line driver to make them RS232 compatible driver is the MAX232 chip

8051 CONNECTION TO RS232


MAX232
converts from RS232 voltage levels to TTL voltage levels uses a +5 V power source MAX232 has two sets of line drivers for transferring and receiving data line drivers used for TxD are called T1 and T2 line drivers for RxD are designated as R1 and R2 T1 and R1 are used together for TxD and RxD of the 8051 second set is left unused

SECTION 10.2: 8051 CONNECTION TO RS232

Figure 7

(a) Inside MAX232 (b) its Connection to the 8051 (Null Modem)

SECTION 10.2: 8051 CONNECTION TO RS232


MAX233
MAX233 performs the same job as the MAX232 eliminates the need for capacitors much more expensive than the MAX232

8051 CONNECTION TO RS232

Figure 8

(a) Inside MAX233 (b) Its Connection to the 8051 (Null Modem)

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY


Baud rate in the 8051
serial communications of the 8051 with the COM port of the PC must make sure that the baud rate of the 8051 system matches the baud rate of the PC's COM port can use Windows HyperTerminal program

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY

Table 3

PC Baud Rates

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY


Baud rate in the 8051
baud rate in the 8051 is programmable done with the help of Timer 1 relationship between the crystal frequency and the baud rate in the 8051 8051 divides the crystal frequency by 12 to get the machine cycle frequency XTAL = 11.0592 MHz, the machine cycle frequency is 921.6 kHz 8051's UART divides the machine cycle frequency of 921.6 kHz by 32 once more before it is used by Timer 1 to set the baud rate 921.6 kHz divided by 32 gives 28,800 Hz Timer 1 must be programmed in mode 2, that is 8-bit, auto-reload

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY

Table 4

Timer 1 TH1 Register Values for Various Baud Rates

Example 1 With XTAL = 11.0592 MHz, find the TH1 value needed to have the following baud rates. (a) 9600 (b) 2400 (c) 1200 machine cycle frequency = 11.0592 MHz / 12 = 921.6 kHz Timer 1 frequency provided by 8051 UART = 921.6 kHz / 32 = 28,800 Hz
(a) 28,800 / 3 = 9600 (b) 28,800 / 12 = 2400 (c) 28,800 / 24 = 1200 where -3 where -12 where -24 = FD (hex) = F4 (hex) = E8 (hex)

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY

11.0592 MHz XTAL oscillator

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY


SBUF (serial buffer) register
a byte of data to be transferred via the TxD line must be placed in the SBUF register SBUF holds the byte of data when it is received by the RxD line can be accessed like any other register
MOV SBUF,#'D' MOV SBUF,A MOV A,SBUF ;load SBUF=44H, ASCII for 'D ;copy accumulator into SBUF ;copy SBUF into accumulator

when a byte is written, it is framed with the start and stop bits and transferred serially via the TxD pin when the bits are received serially via RxD, it is deframe by eliminating the stop and start bits, making a byte out of the data received, and then placing it in the SBUF

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY


SCON (serial control) register
to program the start bit, stop bit, and data bits

Figure 9

SCON Serial Port Control Register (Bit-Addressable)

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY


SM0 and SM1 determine the mode only mode 1 is important when mode 1 is chosen, the data framing is 8 bits, 1 stop bit, and 1 start bit compatible with the COM port of PCs mode 1 allows the baud rate to be variable and is set by Timer 1 of the 8051 for each character a total of 10 bits are transferred, where the first bit is the start bit, followed by 8 bits of data, and finally 1 stop bit.

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY


REN (receive enable) REN=1, allows 8051 to receive data on the RxD if 8051 is to both transfer and receive data, REN must be set to 1 REN=0, the receiver is disabled SETB SCON.4 and CLR SCON.4,

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY


TI (transmit interrupt)
when 8051 finishes the transfer of the 8-bit character, it raises the TI flag to indicate that it is ready to transfer another byte

RI (receive interrupt)
when the 8051 receives data serially via RxD, it places the byte in the SBUF register then raises the RI flag bit to indicate that a byte has been received and should be picked up before it is lost

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY


1. 2. 3. 4. 5. 6.

Program to transfer data serially


TMOD register is loaded with the value 20H TH1 is loaded with value to set the baud rate SCON register is loaded with the value 50H TR1 is set to 1 to start Timer1 TI is cleared by the "CLR TI" instruction transmit character byte is written into the SBUF register 7. TI flag bit is monitored to see if the character has been transferred completely 8. to transfer the next character, go to Step 5.

Example 2 Write a program to transfer letter "A" serially at 4800 baud, continuously.

Example 3 Write a program to transfer the message "YES" serially at 9600 baud, 8-bit data, 1 stop bit. Do this continuously.

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY


Importance of the TI flag
check the TI flag bit, we know whether can transfer another byte TI flag bit is raised by the 8051 TI flag cleared by the programmer writing a byte into SBUF before the TI flag bit is raised, may lead to loss of a portion of the byte being transferred

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY


Program to receive data serially
1. 2. 3. 4. 5. 6. TMOD register is loaded with the value 20H TH1 is loaded with value set the baud rate SCON register is loaded with the value 50H TR1 is set to 1 to start Timer 1 RI is cleared with the "CLR RI" instruction RI flag bit is monitored to see if an entire character has been received yet 7. RI=1 SBUF has the byte, its contents are moved into a safe place 8. to receive the next character, go to Step 5

Example 4 Program the 8051 to receive bytes of data serially, and put them in P1. Set the baud rate at 4800, 8-bit data, and 1 stop bit.

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY


Importance of the RI flag bit
1. it receives the start bit, next bit is the first bit of the character 2. when the last bit is received, a byte is formed and placed in SBUF 3. when stop bit is received, makes RI = 1 4. when RI=1, received byte is in the SBUF register, copy SBUF contents to a safe place 5. after the SBUF contents are copied the RI flag bit must be cleared to 0

8051 SERIAL PORT PROGRAMMING IN ASSEMBLY


Doubling the baud rate in the 8051
two ways to increase the baud rate
1. Use a higher-frequency crystal 2. Change a bit in the PCON register

Table 5

Baud Rate Comparison for SMOD = 0 and SMOD = 1