Two voltage levels can be represented as the two digits 0 and 1 Signals in digital electronics have two distinct voltage levels with built-in tolerances for variations in the voltage A valid digital signal should be within either of the two shaded areas
5 4 3 2 1 0 Logic 1

Execute information stored in memory Provide a means of communicating with CPU RAM (Random Access Memory) – temporary storage of programs that computer is running ROM (Read Only Memory) – contains programs and information essential to operation of the computer
The data is lost when computer is off

The information cannot be changed by use, and is not lost when power is off – It is called nonvolatile memory

Address bus
For a device (memory or I/O) to be recognized by the CPU, it must be assigned an address
The address assigned to a given device must be unique The CPU puts the address on the address bus, and the decoding circuitry finds the device

Data bus
The CPU either gets data from the device or sends data to it

Control bus
Provides read or write signals to the device to indicate if the CPU is asking for information or sending it information
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

25

INSIDE THE COMPUTER More about Data Bus

The more data buses available, the better the CPU
Think of data buses as highway lanes

More data buses mean a more expensive CPU and computer
The average size of data buses in CPUs varies between 8 and 64

Data buses are bidirectional
To receive or send data

The processing power of a computer is related to the size of its buses

The more address buses available, the larger the number of devices that can be addressed The number of locations with which a CPU can communicate is always equal to 2x, where x is the address lines, regardless of the size of the data bus
ex. a CPU with 24 address lines and 16 data lines can provide a total of 224 or 16M bytes of addressable memory Each location can have a maximum of 1 byte of data, since all general-purpose CPUs are byte addressable

ALU (arithmetic/logic unit)
Performs arithmetic functions such as add, subtract, multiply, and divide, and logic functions such as AND, OR, and NOT

Program counter
Points to the address of the next instruction to be executed
As each instruction is executed, the program counter is incremented to point to the address of the next instruction to be executed

Instruction decoder
Interprets the instruction fetched into the CPU
A CPU capable of understanding more instructions requires more transistors to design
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

31

INSIDE THE COMPUTER Internal Working of Computers

Ex. A CPU has registers A, B, C, and D and it has an 8-bit data bus and a 16-bit address bus. The CPU can access memory from addresses 0000 to FFFFH Assume that the code for the CPU to move a value to register A is B0H and the code for adding a value to register A is 04H The action to be performed by the CPU is to put 21H into register A, and then add to register A values 42H and 12H ...

(B0) code for moving a value to register A (21) value to be moved (04) code for adding a value to register A (42) value to be added (04) code for adding a value to register A (12) value to be added (F4) code for halt

From memory location 1402H it fetches code 04H After decoding, the CPU knows that it must add to the contents of register A the byte sitting at the next address (1403) After the CPU brings the value (42H), it provides the contents of register A along with this value to the ALU to perform the addition
It then takes the result of the addition from the ALU’s output and puts it in register A The program counter becomes 1404, the address of the next instruction

General-purpose microprocessors
Must add RAM, ROM, I/O ports, and timers externally to make them functional Make the system bulkier and much more expensive Have the advantage of versatility on the amount of RAM, ROM, and I/O ports

Microcontroller
The fixed amount of on-chip ROM, RAM, and number of I/O ports makes them ideal for many applications in which cost and space are critical In many applications, the space it takes, the power it consumes, and the price per unit are much more critical considerations than the computing power
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
5

An embedded product uses a microprocessor (or microcontroller) to do one task and one task only
There is only one application software that is typically burned into ROM

A PC, in contrast with the embedded system, can be used for any number of applications
It has RAM memory and an operating system that loads a variety of applications into RAM and lets the CPU run them A PC contains or is connected to various embedded products
Each one peripheral has a microcontroller inside it that performs only one task

Many manufactures of general-purpose microprocessors have targeted their microprocessor for the high end of the embedded market
There are times that a microcontroller is inadequate for the task

When a company targets a generalpurpose microprocessor for the embedded market, it optimizes the processor used for embedded systems Very often the terms embedded processor and microcontroller are used interchangeably
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

One of the most critical needs of an embedded system is to decrease power consumption and space In high-performance embedded processors, the trend is to integrate more functions on the CPU chip and let designer decide which features he/she wants to use In many cases using x86 PCs for the high-end embedded applications
Saves money and shortens development time
A vast library of software already written Windows is a widely used and well understood platform

MICROCONTROLLERS AND EMBEDDED PROCESSORS Criteria for Choosing a Microcontroller

Meeting the computing needs of the task at hand efficiently and cost effectively
Speed Packaging Power consumption The amount of RAM and ROM on chip The number of I/O pins and the timer on chip How easy to upgrade to higherperformance or lower power-consumption versions Cost per unit
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
11

HANEL

MICROCONTROLLERS AND EMBEDDED PROCESSORS Criteria for Choosing a Microcontroller
(cont’)

Availability of software development tools, such as compilers, assemblers, and debuggers Wide availability and reliable sources of the microcontroller
The 8051 family has the largest number of diversified (multiple source) suppliers
Intel (original) Atmel Philips/Signetics AMD Infineon (formerly Siemens) Matra Dallas Semiconductor/Maxim

The 8051 became widely popular after allowing other manufactures to make and market any flavor of the 8051, but remaining code-compatible
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
13

The 8 bits of a register are shown from MSB D7 to the LSB D0
With an 8-bit data type, any data larger than 8 bits must be broken into 8-bit chunks before it is processed
most significant bit least significant bit

Notes on programming
Value (proceeded with #) can be loaded directly to registers A, B, or R0 – R7
MOV A, #23H MOV R5, #0F9H
Add a 0 to indicate that F is a hex number and not a letter If it’s not preceded with #, it means to load from a memory location

If values 0 to F moved into an 8-bit register, the rest of the bits are assumed all zeros
“MOV A, #5”, the result will be A=05; i.e., A = 00000101 in binary

Moving a value that is too large into a register will cause an error
MOV
HANEL

;to the accumulator The ADD instruction tells the CPU to add the source byte to register A and put the result in register A Source operand can be either a register or immediate data, but the destination must always be register A
“ADD R4, A” and “ADD R2, #12H” are invalid since A must be the destination of any arithmetic operation MOV A, #25H ;load 25H into A MOV R2, #34H ;load 34H into R2 ADD A, R2 ;add R2 to Accumulator ;(A = A + R2) MOV A, #25H ;load one operand ;into A (A=25H) ADD A, #34H ;add the second ;operand 34H to A
7

There are always many ways to write the same program, depending on the registers used HANEL

An Assembly language instruction consists of four fields:
[label:] Mnemonic [operands] [;comment]
ORG 0 MOV MOV MOV ADD ADD ADD 0H R5, #25H R7, #34H A, #0 A, R5 A, R7 A, #12H ;start(origin) at location ;load 25H into R5 ;load 34H into R7 Directives do not ;load 0 into generate any machine A code R5 to A ;add contents ofand are used ;now A = A + only by the assembler R5 ;add contents of R7 to A ;now A = A + R7 ;add to A value 12H ;now A = A + 12H ;stay in this loop ;end of asm may be at the end of a Comments source file line or on a line by themselves The assembler ignores comments

Structure of Assembly Language
Mnemonics produce opcodes

HERE: SJMP HERE END

The label field allows the program to refer to a line of code by name HANEL

First we use an editor to type a program, many excellent editors or word processors are available that can be used to create and/or edit the program
Notice that the editor must be able to produce an ASCII file For many assemblers, the file names follow the usual DOS conventions, but the source file has the extension “asm“ or “src”, depending on which assembly you are using

The “asm” source file containing the program code created in step 1 is fed to an 8051 assembler
The assembler converts the instructions into machine code The assembler will produce an object file and a list file The extension for the object file is “obj” while the extension for the list file is “lst”

3)

Assembler require a third step called

linking

The linker program takes one or more object code files and produce an absolute object file with the extension “abs” This abs file is used by 8051 trainers that have a monitor program

Next the “abs” file is fed into a program called “OH” (object to hex converter) which creates a file with extension “hex” that is ready to burn into ROM
This program comes with all 8051 assemblers Recent Windows-based assemblers combine step 2 through 4 into one step

The lst (list) file, which is optional, is very useful to the programmer
It lists all the opcodes and addresses as well as errors that the assembler detected The programmer uses the lst file to find the syntax errors or debug
0000 0000 0002 0004 0006 7D25 7F34 7400 2D 2F 2412 ORG MOV MOV MOV ADD ADD ADD 0H R5,#25H R7,#34H A,#0 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 A,R7 ;add contents of R7 to A ;now A = A + R7 A,#12H ;add to A value 12H ;now A = A + 12H SJMP HERE;stay in this loop ;end of asm source file

All 8051 members start at memory address 0000 when they’re powered up
Program Counter has the value of 0000 The first opcode is burned into ROM address 0000H, since this is where the 8051 looks for the first instruction when it is booted We achieve this by the ORG statement in the source program

A step-by-step description of the action of the 8051 upon applying power on it
1.

When 8051 is powered up, the PC has 0000 and starts to fetch the first opcode from location 0000 of program ROM
Upon executing the opcode 7D, the CPU fetches the value 25 and places it in R5 Now one instruction is finished, and then the PC is incremented to point to 0002, containing opcode 7F

2.

Upon executing the opcode 7F, the value 34H is moved into R7
The PC is incremented to 0004

The instruction at location 0004 is executed and now PC = 0006 After the execution of the 1-byte instruction at location 0006, PC = 0007 Upon execution of this 1-byte instruction at 0007, PC is incremented to 0008
This process goes on until all the instructions are fetched and executed The fact that program counter points at the next instruction to be executed explains some microprocessors call it the instruction pointer

8051 microcontroller has only one data type - 8 bits
The size of each register is also 8 bits It is the job of the programmer to break down data larger than 8 bits (00 to FFH, or 0 to 255 in decimal) The data types can be positive or negative

The DB directive is the most widely used data directive in the assembler
It is used to define the 8-bit data When DB is used to define data, the numbers can be in decimal, binary, hex, The “D” after the decimal ASCII formats number is optional, but using
DATA1: DATA2: DATA3: ORG DB DB DB ORG DB ORG DB “B” (binary) and “H” (hexadecimal) for the others is 500H required 28 ;DECIMAL (1C in Hex) 00110101B ;BINARY (35 in Hex) 39H ;HEX 510H Place ASCII in quotation marks The;ASCII NUMBERS ASCII Assembler will assign “2591” code for the numbers or characters 518H “My name is Joe” ;ASCII CHARACTERS

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 and decimal
If the number is not followed by H, it is decimal and the assembler will convert it to hex

END
This indicates to the assembler the end of the source (asm) file The END directive is the last line of an 8051 program
Mean that in the code anything after the END directive is ignored by the 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
When the label appears in the program, its constant value will be substituted for the label

Assume that there is a constant used in many different places in the program, and the programmer wants to change its value throughout
By the use of EQU, one can change it once and the assembler will change all of its occurrences
Use EQU for the counter constant COUNT ... MOV EQU 25 .... R3, #COUNT The constant is used to load the R3 register

The program status word (PSW) register, also referred to as the flag register, is an 8 bit register
Only 6 bits are used
These four are CY (carry), AC (auxiliary carry), P (parity), and OV (overflow) – They are called conditional flags, meaning that they indicate some conditions that resulted after an instruction was executed The PSW3 and PSW4 are designed as RS0 and RS1, and are used to change the bank

The flag bits affected by the ADD instruction are CY, P, AC, and OV
Example 2-2 Show the status of the CY, AC and P flag after the addition of 38H and 2FH in the following instructions. MOV A, #38H ADD A, #2FH ;after the addition A=67H, CY=0 Solution: 38 + 2F 67 00111000 00101111 01100111

CY = 0 since there is no carry beyond the D7 bit AC = 1 since there is a carry from the D3 to the D4 bi P = 1 since the accumulator has an odd number of 1s (it has five 1s) HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
31

FLAG BITS AND PSW REGISTER ADD Instruction And PSW
(cont’)

Example 2-3 Show the status of the CY, AC and P flag after the addition of 9CH and 64H in the following instructions. MOV A, #9CH ADD A, #64H Solution: 9C + 64 100 10011100 01100100 00000000 ;after the addition A=00H, CY=1

CY = 1 since there is a carry beyond the D7 bit AC = 1 since there is a carry from the D3 to the D4 bi P = 0 since the accumulator has an even number of 1s (it has zero 1s)

A total of 32 bytes from locations 00 to 1F hex are set aside for register banks and the stack A total of 16 bytes from locations 20H to 2FH are set aside for bit-addressable read/write memory A total of 80 bytes from locations 30H to 7FH are used for read and write storage, called scratch pad

These 32 bytes are divided into 4 banks of registers in which each bank has 8 registers, R0-R7
RAM location from 0 to 7 are set aside for bank 0 of R0-R7 where R0 is RAM location 0, R1 is RAM location 1, R2 is RAM location 2, and so on, until memory location 7 which belongs to R7 of bank 0 It is much easier to refer to these RAM locations with names such as R0, R1, and so on, than by their memory locations

Register bank 0 is the default when 8051 is powered up
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
36

We can switch to other banks by use of the PSW register
Bits D4 and D3 of the PSW are used to select the desired register bank Use the bit-addressable instructions SETB and CLR to access PSW.4 and PSW.3
PSW bank selection
Bank 0 Bank 1 Bank 2 Bank 3
RS1(PSW.4) RS0(PSW.3)

The stack is a section of RAM used by the CPU to store information temporarily
This information could be data or an address

The register used to access the stack is called the SP (stack pointer) register
The stack pointer in the 8051 is only 8 bit wide, which means that it can take value of 00 to FFH When the 8051 is powered up, the SP register contains value 07
RAM location 08 is the first location begin used for the stack by the 8051

The storing of a CPU register in the stack is called a PUSH
SP is pointing to the last used location of the stack As we push data onto the stack, the SP is incremented by one
This is different from many microprocessors

Stack

Loading the contents of the stack back into a CPU register is called a POP
With every pop, the top byte of the stack is copied to the register specified by the instruction and the stack pointer is decremented once
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

Because locations 20-2FH of RAM are reserved for bit-addressable memory, so we can change the SP to other RAM location by using the instruction “MOV SP, #XX” HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
43

8051 REGISTER BANKS AND STACK CALL Instruction And Stack

The CPU also uses the stack to save the address of the instruction just below the CALL instruction
This is how the CPU knows where to resume when it returns from the called subroutine

The reason of incrementing SP after push is
Make sure that the stack is growing toward RAM location 7FH, from lower to upper addresses Ensure that the stack will not reach the bottom of RAM and consequently run out of stack space If the stack pointer were decremented after push
We would be using RAM locations 7, 6, 5, etc. which belong to R7 to R0 of bank 0, the default register bank

Repeating a sequence of instructions a certain number of times is called a

loop

Loop action is performed by DJNZ reg, Label
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 loop the register is loaded with the counter for the number of repetitions Counter can be R0 – R7 or RAM location

If we want to repeat an action more times than 256, we use a loop inside a loop, which is called nested loop
We use multiple registers to hold the count
Write a program to (a) load the accumulator with the value 55H, and (b) complement the ACC 700 times MOV MOV NEXT: MOV AGAIN: CPL DJNZ DJNZ A,#55H ;A=55H R3,#10 ;R3=10, outer loop count R2,#70 ;R2=70, inner loop count A ;complement A register R2,AGAIN ;repeat it 70 times R3,NEXT

All conditional jumps are short jumps
The address of the target must within -128 to +127 bytes of the contents of PC
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

6

The unconditional jump is a jump in LOOP AND which control is transferred JUMP unconditionally to the target location INSTRUCTIONS LJMP (long jump)
Unconditional Jumps 3-byte instruction
First byte is the opcode Second and third bytes represent the 16-bit target address – Any memory location from 0000 to FFFFH SJMP

(short jump)
2-byte instruction
First byte is the opcode Second byte is the relative target address – 00 to FFH (forward +127 and backward -128 bytes from the current PC)

Call instruction is used to call 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
LCALL

(long call)
First byte is the opcode Second and third bytes are used for address of target subroutine – Subroutine is located anywhere within 64K byte address space

When a subroutine is called, control is transferred to that subroutine, the processor
Saves on the stack the the address of the instruction immediately below the LCALL Begins to fetch instructions form the new location

After finishing execution of the subroutine
The instruction RET transfers control back to the caller
Every subroutine needs RET as the last instruction
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

HANEL

11

CALL INSTRUCTIONS LCALL
(cont’)

BACK:

ORG MOV MOV LCALL MOV MOV LCALL SJMP

0 A,#55H P1,A DELAY A,#0AAH P1,A DELAY BACK

;load ;send ;time ;load ;send

A with 55H to delay A with AAH to

55H port 1 AA (in hex) port 1

;keep doing this indefinitely

The counter R5 is set to FFH; so loop is repeated 255 times.

Upon executing “LCALL DELAY”, the address of instruction below it, “MOV A,#0AAH” is pushed onto stack, and the 8051 starts to execute at 300H.

;MAIN program calling subroutines ORG 0 It is common to have one MAIN: LCALL SUBR_1 main program and many LCALL SUBR_2 subroutines that are called LCALL SUBR_3

from the main program
HERE: SJMP HERE ;-----------end of MAIN SUBR_1: ... ... RET ;-----------end of subroutine1 SUBR_2: ... ... RET ;-----------end of subroutine2

SUBR_3: ... ... RET ;-----------end of subroutine3 END ;end of the asm file

This allows you to make each subroutine into a separate module - Each module can be tested separately and then brought together with main program - In a large program, the module can be assigned to different programmers

A rewritten program which is more efficiently
ORG MOV MOV ACALL CPL SJMP ... END 0 A,#55H P1,A DELAY A BACK ;load A with 55H ;send 55H to port 1 ;time delay ;complement reg A ;keep doing this indefinitely ;end of asm file

CPU executing an instruction takes a certain number of clock cycles
These are referred as to as machine cycles

The length of machine cycle depends on the frequency of the crystal oscillator connected to 8051 In original 8051, one machine cycle lasts 12 oscillator periods
Find the period of the machine cycle for 11.0592 MHz crystal frequency
Solution:

Find the size of the delay in following program, if the crystal frequency is 11.0592MHz. Machine Cycle DELAY: MOV R2,#200 1 Notice in nested loop, AGAIN: MOV R3,#250 1 as in all other time HERE: NOP 1 delay loops, the time NOP 1 is approximate since DJNZ R3,HERE 2 we have ignored the DJNZ R2,AGAIN 2 first and last RET 2 instructions in the subroutine. Solution: For HERE loop, we have (4x250)x1.085μs＝1085μs. For AGAIN loop repeats HERE loop 200 times, so we have 200x1085μs＝217000μs. But “MOV R3,#250” and “DJNZ R2,AGAIN” at the start and end of the AGAIN loop add (3x200x1.805)=651μs. As a result we have 217000+651=217651μs.

The four 8-bit I/O ports P0, P1, P2 and P3 each uses 8 pins All the ports upon RESET are configured as input, 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

It can be used for input or output, each pin must be connected externally to a 10K ohm pull-up resistor
This is due to the fact that P0 is an open drain, unlike P1, P2, and P3
same way that open collector is used for TTL chips
Vcc

In order to make port 0 an input, the port must be programmed by writing 1 to all the bits
Port 0 is configured first as an input port by writing 1s to it, and then data is received from that port and sent to P1 MOV MOV BACK: A,#0FFH P0,A A,P0 P1,A BACK ;A=FF hex ;make P0 an i/p port ;by writing it all 1s ;get data from P0 ;send it to port 1 ;keep doing it

Port 1 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 0 the alternating value 55H and AAH

To make port 1 an input port, it must be programmed as such by writing 1 to all its bits
Port 1 is configured first as an input port by writing 1s to it, then data is received from that port and saved in R7 and R5 MOV MOV MOV MOV ACALL MOV MOV A,#0FFH P1,A A,P1 R7,A DELAY A,P1 R5,A ;A=FF hex ;make P1 an input port ;by writing it all 1s ;get data from P1 ;save it to in reg R7 ;wait ;another data from P1 ;save it to in reg R5

To make port 2 an input port, it must be programmed as such by writing 1 to all its bits In many 8051-based system, P2 is used as simple I/O In 8031-based systems, port 2 must be used along with P0 to provide the 16bit address for the external memory
Port 2 is also designated as A8 – A15, indicating its dual function Port 0 provides the lower 8 bits via A0 – A7

Example 4-2 Write the following programs. Create a square wave of 50% duty cycle on bit 0 of port 1. Solution: The 50% duty cycle means that the “on” and “off” state (or the high and low portion of the pulse) have the same length. Therefore, we toggle P1.0 with a time delay in between each state. HERE: SETB P1.0 ;set to high bit 0 of port 1 LCALL DELAY ;call the delay subroutine CLR P1.0 ;P1.0=0 LCALL DELAY SJMP HERE ;keep doing it Another way to write the above program is: HERE: CPL P1.0 ;set to high bit 0 of port 1 LCALL DELAY ;call the delay subroutine SJMP HERE ;keep doing it
8051

The JNB and JB instructions are widely used single-bit operations
They allow you to monitor a bit and make a decision depending on whether it’s 0 or 1 These two instructions can be used for any bits of I/O ports 0, 1, 2, and 3
Port 3 is typically not used for any I/O, either single-bit or byte-wise
Instructions for Reading an Input Port
Mnemonic MOV A,PX JNB PX.Y, .. JB PX.Y, .. MOV C,PX.Y Examples MOV A,P2 JNB P2.1,TARGET JB P1.3,TARGET MOV C,P2.4 Description Bring into A the data at P2 pins Jump if pin P2.1 is low Jump if pin P1.3 is high Copy status of pin P2.4 to CY

Example 4-4 Assume that bit P2.3 is an input and represents the condition of an oven. If it goes high, it means that the oven is hot. Monitor the bit continuously. Whenever it goes high, send a high-to-low pulse to port P1.5 to turn on a buzzer. Solution: HERE: JNB SETB CLR SJMP P2.3,HERE P1.5 P1.5 HERE ;keep monitoring for high ;set bit P1.5=1 ;make high-to-low ;keep repeating

Example 4-7 A switch is connected to pin P1.0 and an LED to pin P2.7. Write a program to get the status of the switch and send it to the LED Solution: SETB AGAIN: MOV MOV SJMP P1.7 C,P1.0 P2.7,C AGAIN ;make ;read ;send ;keep P1.7 an input SW status into CF SW status to LED repeating

However ‘MOV P2,P1’ is a valid instruction

The instruction ‘MOV P2.7,P1.0’ is wrong , since such an instruction does not exist

Some instructions read the contents of an internal port latch instead of reading the status of an external pin
For example, look at the ANL P1,A instruction and the sequence of actions is executed as follow
1. It reads the internal latch of the port and brings that data into the CPU 2. This data is ANDed with the contents of register A 3. The result is rewritten back to the port latch 4. The port pin data is changed and now has the same value as port latch

The ports in 8051 can be accessed by the Read-modify-write technique
This feature saves many lines of code by combining in a single instruction all three actions
1. Reading the port 2. Modifying it 3. Writing to the port
MOV AGAIN: XRL ACALL SJMP P1,#55H ;P1=01010101 P1,#0FFH ;EX-OR P1 with 1111 1111 DELAY BACK

The source operand is a constant
The immediate data must be preceded by the pound sign, “#” Can load information into any registers, including 16-bit DPTR register
DPTR can also be accessed as two 8-bit registers, the high byte DPH and low byte DPL
MOV MOV MOV MOV MOV MOV A,#25H R4,#62 B,#40H DPTR,#4521H DPL,#21H DPH,#45H ;load 25H into A ;load 62 into R4 ;load 40H into B ;DPTR=4512H ;This is the same ;as above

Use registers to hold the data to be manipulated
MOV MOV ADD ADD MOV A,R0 R2,A A,R5 A,R7 R6,A ;copy contents of R0 into A ;copy contents of A into R2 ;add contents of R5 to A ;add contents of R7 to A ;save accumulator in R6

The source and destination registers must match in size
MOV DPTR,A

will give an error

MOV DPTR,#25F5H MOV R7,DPL MOV R6,DPH

The movement of data between Rn registers is not allowed
MOV R4,R7
HANEL

It is most often used the direct addressing mode to access RAM locations 30 – 7FH
The entire 128 bytes of RAM can be accessed Direct addressing mode The register bank locations are accessed by the register names
MOV A,4 MOV A,R4 ;is same as ;which means copy R4 into A

Contrast this with immediate Register addressing mode addressing mode
There is no “#” sign in the operand
MOV R0,40H MOV 56H,A HANEL ;save content of 40H in R0 ;save content of A in 56H
6

The SFR (Special Function Register) can be accessed by their names or by their addresses
MOV 0E0H,#55H MOV A,#55h MOV 0F0H,R0 MOV B,R0 ;is the same as ;load 55H into A ;is the same as ;copy R0 into B

The SFR registers have addresses between 80H and FFH
Not all the address space of 80 to FF is used by SFR The unused locations 80H to FFH are reserved and must not be used by the 8051 programmer
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
7

Only direct addressing mode is allowed for pushing or popping the stack
PUSH A is invalid Pushing the accumulator onto the stack must be coded as PUSH 0E0H
Example 5-2 Show the code to push R5 and A onto the stack and then pop them back them into R2 and B, where B = A and R2 = R5 Solution: PUSH 05 PUSH 0E0H POP 0F0H POP 02 ;push R5 onto stack ;push register A onto stack ;pop top of stack into B ;now register B = register A ;pop top of stack into R2 ;now R2=R6

A register is used as a pointer to the data
Only register R0 and R1 are used for this purpose R2 – R7 cannot be used to hold the address of an operand located in RAM

When R0 and R1 hold the addresses of RAM locations, they must be preceded by the “@” sign
MOV A,@R0 MOV @R1,B ;move contents of RAM whose ;address is held by R0 into A ;move contents of B into RAM ;whose address is held by R1

R0 and R1 are the only registers that can be used for pointers in register indirect addressing mode Since R0 and R1 are 8 bits wide, their use is limited to access any information in the internal RAM Whether accessing externally connected RAM or on-chip ROM, we need 16-bit pointer
In such case, the DPTR register is used

Indexed addressing mode is widely used in accessing data elements of look-up table entries located in the program ROM The instruction used for this purpose is
MOVC A,@A+DPTR Use instruction MOVC, “C” means code The contents of A are added to the 16-bit register DPTR to form the 16-bit address of the needed data

In this program, assume that the word “USA” is burned into ROM locations starting at 200H. And that the program is burned into ROM locations starting at 0. Analyze how the program works and state where “USA” is stored after this program is run.

In many applications, the size of program code does not leave any room to share the 64K-byte code space with data
The 8051 has another 64K bytes of memory space set aside exclusively for data storage
This data memory space is referred to as external memory and it is accessed only by the MOVX instruction

The 8051 has a total of 128K bytes of memory space
64K bytes of code and 64K bytes of data The data space cannot be shared between code and data
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
20

Many microprocessors allow program to access registers and I/O ports in byte size only
However, in many applications we need to check a single bit

One unique and powerful feature of the 8051 is single-bit operation
Single-bit instructions allow the programmer to set, clear, move, and complement individual bits of a port, memory, or register It is registers, RAM, and I/O ports that need to be bit-addressable
ROM, holding program code for execution, is not bit-addressable
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

While all of the SFR registers are byteaddressable, some of them are also bitaddressable
The P0 – P3 are bit addressable

We can access either the entire 8 bits or any single bit of I/O ports P0, P1, P2, and P3 without altering the rest When accessing a port in a single-bit manner, we use the syntax SETB X.Y
X is the port number P0, P1, P2, or P3 Y is the desired bit number from 0 to 7 for data bits D0 to D7 ex. SETB P1.5 sets bit 5 of port 1 high
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

HANEL

28

BIT ADDRESSES I/O Port Bit Addresses
(cont’)

Notice that when code such as SETB P1.0 is assembled, it becomes
SETB 90H The bit address for I/O ports
P0 P1 P2 P3 are are are are 80H to 87H 90H to 97H A0H to A7H B0H to B7H

Only registers A, B, PSW, IP, IE, ACC, SCON, and TCON are bit-addressable
While all I/O ports are bit-addressable

In PSW register, two bits are set aside for the selection of the register banks
Upon RESET, bank 0 is selected We can select any other banks using the bit-addressability of the PSW
CY AC -RS1 RS0 OV -P

Example 5-14 While there are instructions such as JNC and JC to check the carry flag bit (CY), there are no such instructions for the overflow flag bit (OV). How would you write code to check OV? Solution:
JB
CY AC

PSW.2,TARGET
-RS1

;jump if OV=1
RS0 OV -P

Example 5-18 While a program to save the status of bit P1.7 on RAM address bit 05. Solution:
MOV MOV C,P1.7 05,C

Example 5-15 Write a program to see if the RAM location 37H contains an even value. If so, send it to P2. If not, make it even and then send it to P2. Solution:
MOV JNB INC MOV A,37H ;load RAM 37H into ACC ACC.0,YES ;if D0 of ACC 0? If so jump A ;it’s odd, make it even P2,A ;send it to P2

The BIT directive is a widely used directive to assign the bit-addressable I/O and RAM locations
Allow a program to assign the I/O or RAM bit at the beginning of the program, making it easier to modify them
Example 5-22 A switch is connected to pin P1.7 and an LED to pin P2.0. Write a program to get the status of the switch and send it to the LED. Solution:
LED SW HERE: BIT BIT MOV MOV SJMP P1.7 P2.0 C,SW LED,C HERE ;assign bit ;assign bit ;get the bit from the port ;send the bit to the port ;repeat forever

The 8052 has another 128 bytes of onchip RAM with addresses 80 – FFH
It is often called upper memory
Use indirect addressing mode, which uses R0 and R1 registers as pointers with values of 80H or higher – MOV @R0, A and MOV @R1, A

The same address space assigned to the SFRs
Use direct addressing mode – MOV 90H, #55H is the same as MOV P1, #55H

The instruction ADD is used to add two operands
Destination operand is always in register A Source operand can be a register, immediate data, or in memory Memory-to-memory arithmetic operations are never allowed in 8051 Assembly language
Show how the flag register is affected by the following instruction. MOV A,#0F5H ;A=F5 hex CY =1, since there is a ADD A,#0BH ;A=F5+0B=00 carry out from D7 Solution: + F5H 0BH 100H 1111 0101 + 0000 1011 0000 0000
PF =1, because the number of 1s is zero (an even number), PF is set to 1. AC =1, since there is a carry from D3 to D4

When adding two 16-bit data operands, the propagation of a carry from lower byte to higher byte is concerned
+ 1 3C E7 3B 8D 78 74 When the first byte is added (E7+8D=74, CY=1). The carry is propagated to the higher byte, which result in 3C + 3B + 1 =78 (all in hex)

Write a program to add two 16-bit numbers. Place the sum in R7 and R6; R6 should have the lower byte. Solution:
CLR MOV ADD MOV MOV ADDC MOV C A, #0E7H A, #8DH R6, A A, #3CH A, #3BH R7, A ;make CY=0 ;load the low byte now A=E7H ;add the low byte ;save the low byte sum in R6 ;load the high byte ;add with the carry ;save the high byte sum

The “DA” instruction works only on A. In other word, while the source can be an operand of any addressing mode, the destination must be in register A in order for DA to work.
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

Since AC=1 after the addition, ”DA A” will add 6 to the lower nibble. The final result is in BCD format. HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
8

In many microprocessor there are two different instructions for subtraction: SUB and SUBB (subtract with borrow)
In the 8051 we have only SUBB The 8051 uses adder circuitry to perform the subtraction SUBB A,source ;A = A – source – CY

To make SUB out of SUBB, we have to make CY=0 prior to the execution of the instruction
Notice that we use the CY flag for the borrow

Take the 2’s complement of the subtrahend (source operand) Add it to the minuend (A) Invert the carry
CLR MOV SUBB JNC CPL INC MOV C A,#4C ;load A with value 4CH A,#6EH ;subtract 6E from A NEXT ;if CY=0 jump to NEXT A ;if CY=1, take 1’s complement A ;and increment to get 2’s comp R1,A ;save A in R1
2’s complement +

NEXT: Solution:
CY=0, the result is positive; CY=1, the result is negative and the destination has the 2’s complement of the result

If the result of an operation on signed numbers is too large for the register An overflow has occurred and the programmer must be noticed
Examine the following code and analyze the result. MOV MOV ADD Solution: +96 + +70 + 166 0110 0000 0100 0110 1010 0110 and OV =1 A,#+96 R1,#+70 A,R1 ;A=0110 0000 (A=60H) ;R1=0100 0110(R1=46H) ;A=1010 0110 ;A=A6H=-90,INVALID

According to the CPU, the result is -90, which is wrong. The CPU sets OV=1 to indicate the overflow
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

HANEL

18

SIGNED ARITHMETIC INSTRUCTIONS OV Flag

In 8-bit signed number operations, OV is set to 1 if either occurs:
1. 2.

There is a carry from D6 to D7, but no carry out of D7 (CY=0) There is a carry from D7 out (CY=1), but no carry from D6 to D7
;A=1000 0000(A=80H) ;R4=1111 1110(R4=FEH) ;A=0111 1110(A=7EH=+126,INVALID) 1000 0000 1111 1110 0111 1110 and OV=1 OV = 1 The result +126 is wrong

This instruction will perform a logic AND on the two operands and place the result in the destination
The destination is normally the accumulator The source operand can be a register, in memory, or immediate
Show the results of the following. MOV ANL 35H 0FH 05H ;A = 35H ;A = A AND 0FH ANL is often used to 0 0 1 1 0 1 0 1 mask (set to 0) certain 0 0 0 0 1 1 1 1 bits of an operand 0 0 0 0 0 1 0 1 A,#35H A,#0FH

The destination and source operands are ORed and the result is placed in the destination
The destination is normally the accumulator The source operand can be a register, in memory, or immediate
Show the results of the following. MOV ORL 04H 68H 6CH A,#04H A,#68H ;A = 04 ;A = 6C ORL instruction can be used to set certain bits of an operand to 1

This instruction will perform XOR operation on the two operands and place the result in the destination
The destination is normally the accumulator The source operand can be a register, in memory, or immediate

Read and test P1 to see whether it has the value 45H. If it does, send 99H to P2; otherwise, it stays cleared. XRL can be used to see if two registers Solution: MOV P2,#00 ;clear P2 have the same value MOV P1,#0FFH ;make P1 an input port MOV R3,#45H ;R3=45H MOV A,P1 ;read P1 XRL A,R3 JNZ EXIT ;jump if A is not 0 MOV P2,#99H EXIT: ... If both registers have the same value, 00 is placed in A. JNZ and JZ test the contents of the Department of Computer Science and Information Engineering accumulator.
National Cheng Kung University, TAIWAN
26

The actions of comparing and jumping are combined into a single instruction called CJNE (compare and jump if not equal)
The CJNE instruction compares two operands, and jumps if they are not equal The destination operand can be in the accumulator or in one of the Rn registers The source operand can be in a register, in memory, or immediate
The operands themselves remain unchanged

It changes the CY flag to indicate if the destination operand is larger or smaller
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
28

The compare instruction is really a subtraction, except that the operands remain unchanged
Flags are changed according to the execution of the SUBB instruction
Write a program to read the temperature and test it for the value 75. According to the test results, place the temperature value into the registers indicated by the following. If T = 75 then A = 75 If T < 75 then R1 = T If T > 75 then R2 = T Solution:
MOV MOV CJNE SJMP JNC MOV SJMP MOV ... P1,#0FFH A,P1 A,#75,OVER EXIT NEXT R1,A EXIT R2,A ;make P1 an input port ;read P1 port ;jump if A is not 75 ;A=75, exit ;if CY=0 then A>75 ;CY=1, A<75, save in R1 ; and exit ;A>75, save it in R2

Serializing data is a way of sending a byte of data one bit at a time through a single pin of microcontroller
Using the serial port, discussed in Chapter 10 To transfer data one bit at a time and control the sequence of data and spaces in between them

Write a program to bring in a byte of data serially one bit at a time via pin P2.7 and save it in register R2. The byte comes in with the LSB first. Solution: MOV AGAIN: MOV RRC DJNZ MOV R5,#8 C,P2.7 A R5,HERE R2,A ;bring in bit ;save it

Function
Make CY = 1 Clear carry bit (CY = 0) Complement carry bit Copy carry status to bit location (CY = b) Copy bit location status to carry (b = CY) Jump to target if CY = 0 Jump to target if CY = 1 AND CY with bit and save it on CY AND CY with inverted bit and save it on CY OR CY with bit and save it on CY OR CY with inverted bit and save it on CY

Assume that bit P2.2 is used to control an outdoor light and bit P2.5 a light inside a building. Show how to turn on the outside light and turn off the inside one. Solution: SETB ORL MOV CLR ANL MOV C C,P2.2 P2.2,C C C,P2.5 P2.5,C ;CY = 1 ;CY = P2.2 ORed w/ CY ;turn it on if not on ;CY = 0 ;CY = P2.5 ANDed w/ CY ;turn it off if not off

Single-bit Operations with CY
(cont’)
Solution:

Write a program that finds the number of 1s in a given byte. MOV MOV MOV AGAIN: RLC JNC INC NEXT: DJNZ R1,#0 ;R1 keeps number of 1s R7,#8 ;counter, rotate 8 times A,#97H ;find number of 1s in 97H A ;rotate it thru CY NEXT ;check CY R1 ;if CY=1, inc count R7,AGAIN ;go thru 8 times

The DS5000T microcontrollers have a real-time clock (RTC)
The RTC provides the time of day (hour, minute, second) and the date (year, month, day) continuously, regardless of whether the power is on or off

Assume that register A has packed BCD, write a program to convert packed BCD to two ASCII numbers and place them in R2 and R6. MOV MOV ANL ORL MOV MOV data ANL RR RR RR RR ORL MOV A,#29H ;A=29H, packed BCD R2,A ;keep a copy of BCD data A,#0FH ;mask the upper nibble (A=09) A,#30H ;make it an ASCII, A=39H(‘9’) R6,A ;save it A,R2 ;A=29H, get the original A,#0F0H A A A A A,#30H R2,A ;mask the lower nibble ;rotate right ;rotate right SWAP A ;rotate right ;rotate right ;A=32H, ASCII char. ’2’ ;save ASCII char in R2

To ensure the integrity of the ROM contents, every system must perform the checksum calculation
The process of checksum will detect any corruption of the contents of ROM The checksum process uses what is called a checksum byte
The checksum byte is an extra byte that is tagged to the end of series of bytes of data

Assume that we have 4 bytes of hexadecimal data: 25H, 62H, 3FH, and 52H.(a) Find the checksum byte, (b) perform the checksum operation to ensure data integrity, and (c) if the second byte 62H has been changed to 22H, show how checksum detects the error. Solution: (a) Find the checksum byte. 25H The checksum is calculated by first adding the + 62H bytes. The sum is 118H, and dropping the carry, + 3FH we get 18H. The checksum byte is the 2’s + 52H complement of 18H, which is E8H 118H (b) Perform the checksum operation to ensure data integrity. 25H + 62H Adding the series of bytes including the checksum + 3FH byte must result in zero. This indicates that all the + 52H bytes are unchanged and no byte is corrupted. + E8H 200H (dropping the carries) (c) If the second byte 62H has been changed to 22H, show how checksum detects the error. 25H + 22H Adding the series of bytes including the checksum + 3FH byte shows that the result is not zero, which indicates + 52H that one or more bytes have been corrupted. + E8H 1C0H (dropping the carry, we get C0H) Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

Compilers produce hex files that is downloaded to ROM of microcontroller
The size of hex file is the main concern
Microcontrollers have limited on-chip ROM Code space for 8051 is limited to 64K bytes

C programming is less time consuming, but has larger hex file size The reasons for writing programs in C
It is easier and less time consuming to write in C than Assembly C is easier to modify and update You can use code available in function libraries C code is portable to other microcontroller with little of no modification
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
2

DATA TYPES

A good understanding of C data types for 8051 can help programmers to create smaller hex files
Unsigned char Signed char Unsigned int Signed int Sbit (single bit) Bit and sfr

The signed char is an 8-bit data type
DATA TYPES Signed char Use the MSB D7 to represent – or + Give us values from –128 to +127

We should stick with the unsigned char unless the data needs to be represented as signed numbers
temperature
Write an 8051 C program to send values of –4 to +4 to port P1. Solution: //Singed numbers #include <reg51.h> void main(void) { char mynum[]={+1,-1,+2,-2,+3,-3,+4,-4}; unsigned char z; for (z=0;z<=8;z++) P1=mynum[z]; }

The unsigned int is a 16-bit data type
Takes a value in the range of 0 to 65535 (0000 – FFFFH) Define 16-bit variables such as memory addresses Set counter values of more than 256 Since registers and memory accesses are in 8-bit chunks, the misuse of int variables will result in a larger hex file

Signed int is a 16-bit data type
Use the MSB D15 to represent – or + We have 15 bits for the magnitude of the number from –32768 to +32767
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

8

DATA TYPES Single Bit
(cont’)

Write an 8051 C program to toggle bit D0 of the port P1 (P1.0) 50,000 times. Solution: #include <reg51.h> sbit MYBIT=P1^0; sbit keyword allows access to the single bits of the SFR registers

There are two way s to create a time delay in 8051 C
Using the 8051 timer (Chap. 9) Using a simple for loop be mindful of three factors that can affect the accuracy of the delay
The 8051 design – The number of machine cycle – The number of clock periods per machine cycle The crystal frequency connected to the X1 – X2 input pins Compiler choice – C compiler converts the C statements and functions to Assembly language instructions – Different compilers produce different code

Write an 8051 C program to toggle bits of P1 continuously forever with some delay. Solution: //Toggle P1 forever with some delay in between //“on” and “off” #include <reg51.h> We must use the oscilloscope to void main(void) measure the exact duration { unsigned int x; for (;;) //repeat forever { p1=0x55; for (x=0;x<40000;x++); //delay size //unknown p1=0xAA; for (x=0;x<40000;x++); } }

Write an 8051 C program to get a byte of data form P0. If it is less than 100, send it to P1; otherwise, send it to P2. Solution: #include <reg51.h> void main(void) { unsigned char mybyte; P0=0xFF; while (1) { mybyte=P0; if (mybyte<100) P1=mybyte; else P2=mybyte; } }

//make P0 input port //get a byte from P0 //send it to P1 //send it to P2

Write an 8051 C program to toggle only bit P2.4 continuously without disturbing the rest of the bits of P2. Ports P0 – P3 are bitSolution: addressable and we use //Toggling an individual bit sbit data type to access #include <reg51.h> a single bit of P0 - P3 sbit mybit=P2^4; void main(void) { while (1) { mybit=1; mybit=0; } } Use the Px^y format, where x is the port 0, 1, 2, or 3 and y is the bit 0 – 7 of that port //turn on P2.4 //turn off P2.4

A door sensor is connected to the P1.1 pin, and a buzzer is connected to P1.7. Write an 8051 C program to monitor the door sensor, and when it opens, sound the buzzer. You can sound the buzzer by sending a square wave of a few hundred Hz. Solution: #include <reg51.h> void MSDelay(unsigned int); sbit Dsensor=P1^1; sbit Buzzer=P1^7; void main(void) { Dsensor=1; //make P1.1 an input while (1) { while (Dsensor==1)//while it opens { Buzzer=0; MSDelay(200); Buzzer=1; MSDelay(200); } } }

The data pins of an LCD are connected to P1. The information is latched into the LCD whenever its Enable pin goes from high to low. Write an 8051 C program to send “The Earth is but One Country” to this LCD. Solution: #include <reg51.h> #define LCDData P1 sbit En=P2^0; //LCDData declaration //the enable pin

Write an 8051 C program to turn bit P1.5 on and off 50,000 times. Solution: sbit MYBIT=0x95; We can access a single bit of any SFR if we specify the bit address

void main(void) { unsigned int z; for (z=0;z<50000;z++) { MYBIT=1; MYBIT=0; } } Notice that there is no #include <reg51.h>. This allows us to access any byte of the SFR RAM space 80 – FFH. This is widely used for the new generation of 8051 microcontrollers.
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

HANEL

22

I/O PROGRAMMING Using bit Data Type for Bit-addressable RAM

Write an 8051 C program to get the status of bit P1.0, save it, and send it to P2.7 continuously. Solution: #include <reg51.h> sbit inbit=P1^0; sbit outbit=P2^7; bit membit;

//use bit to declare //bit- addressable memory

We use bit data type to access void main(void) data in a bit-addressable section { of the data RAM space 20 – 2FH while (1) { membit=inbit; //get a bit from P1.0 outbit=membit; //send it to P2.7 } }

The 8051 C compiler allocates RAM locations
Bank 0 – addresses 0 – 7 Individual variables – addresses 08 and beyond Array elements – addresses right after variables
Array elements need contiguous RAM locations and that limits the size of the array due to the fact that we have only 128 bytes of RAM for everything

Compile and single-step the following program on your 8051 simulator. Examine the contents of the code space to locate the ASCII values. To make the C compiler use the Solution: code space instead of the RAM space, we need to put the #include <reg51.h> keyword code in front of the variable declaration void main(void) { code unsigned char mynum[]=“ABCDEF”; unsigned char z; for (z=0;z<=6;z++) P1=mynum[z]; }

Compare and contrast the following programs and discuss the advantages and disadvantages of each one. (a) #include <reg51.h> void main(void) { P1=‘H’; P1=‘E’; P1=‘L’; P1=‘L’; P1=‘O’; } ... Short and simple, but the individual characters are embedded into the program and it mixes the code and data together

... (b) #include <reg51.h> void main(void) { unsigned char mydata[]=“HELLO”; unsigned char z; for (z=0;z<=5;z++) Use a separate area of the P1=mydata[z]; } code space for data. This allows the size of the array to (c) be as long as you want if you #include <reg51.h> have the on-chip ROM. void main(void) { code unsigned char mydata[]=“HELLO”; unsigned char z; for (z=0;z<=5;z++) P1=mydata[z]; } However, the more code space you use for data, the less space is left for your program code
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

Use the RAM data space to store array elements, therefore the size of the array is limited

HANEL

41

DATA SERIALIZATION

Serializing data is a way of sending a byte of data one bit at a time through a single pin of microcontroller
Using the serial port (Chap. 10) Transfer data one bit a time and control the sequence of data and spaces in between them
In many new generations of devices such as LCD, ADC, and ROM the serial versions are becoming popular since they take less space on a PCB

8051 family members (e.g, 8751, 89C51, 89C52, DS89C4x0)
Have 40 pins dedicated for various functions such as I/O, -RD, -WR, address, data, and interrupts Come in different packages, such as
DIP(dual in-line package), QFP(quad flat package), and LLC(leadless chip carrier)

Some companies provide a 20-pin version of the 8051 with a reduced number of I/O ports for less demanding applications

Vcc, GND, XTAL1, XTAL2, RST, -EA are used by all members of 8051 and 8031 families

P3

P2

Grond

-PSEN and ALE are used mainly in 8031-baded systems HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

4

PIN DESCRIPTION XTAL1 and XTAL2

The 8051 has an on-chip oscillator but requires an external clock to run it
A quartz crystal oscillator is connected to inputs XTAL1 (pin19) and XTAL2 (pin18)
The quartz crystal oscillator also needs two capacitors of 30 pF value
C2 XTAL2

The speed of 8051 refers to the maximum oscillator frequency connected to XTAL
ex. A 12-MHz chip must be connected to a crystal with 12 MHz frequency or less We can observe the frequency on the XTAL2 pin using the oscilloscope

RESET pin is an input and is active high (normally low)
Upon applying a high pulse to this pin, the microcontroller will reset and terminate all activities
This is often referred to as a power-on reset Activating a power-on reset will cause all values in the registers to be lost

In order for the RESET input to be effective, it must have a minimum duration of 2 machine cycles
In other words, the high pulse must be high for a minimum of 2 machine cycles before it is allowed to go low
Power-on RESET circuit Power-on RESET with debounce
Vcc
31 + 10 uF 30 pF 8.2K 30 pF 11.0592 MHz 18 9 X2 RST 19 EA/Vpp X1

Port 0 provides both address and data
The 8031 multiplexes address and data through port 0 to save pins ALE pin is used for demultiplexing the address and data by connecting to the G pin of the 74LS373 chip

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 ALE indicates if P0 has address or data
When ALE=0, it provides data D0-D7 When ALE=1, it has address A0-A7

It can be used for input or output, each pin must be connected externally to a 10K ohm pull-up resistor
This is due to the fact that P0 is an open drain, unlike P1, P2, and P3
Open drain is a term used for MOS chips in the same way that open collector is used for TTL chips
Vcc

In 8051-based systems with no external memory connection
Both P1 and P2 are used as simple I/O

In 8031/51-based systems with external memory connections
Port 2 must be used along with P0 to provide the 16-bit address for the external memory
P0 provides the lower 8 bits via A0 – A7 P2 is used for the upper 8 bits of the 16-bit address, designated as A8 – A15, and it cannot be used for I/O

Intel hex file is a widely used file format
Designed to standardize the loading of executable machine codes into a ROM chip

Loaders that come with every ROM burner (programmer) support the Intel hex file format
In many newer Windows-based assemblers the Intel hex file is produced automatically (by selecting the right setting) In DOS-based PC you need a utility called OH (object-to-hex) to produce that
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

17

EXPLAINING INTEL HEX FILE
(cont’)

In the DOS environment
The object file is fed into the linker program to produce the abs file
The abs file is used by systems that have a monitor program

Then the abs file is fed into the OH utility to create the Intel hex file
The hex file is used only by the loader of an EPROM programmer to load it into the ROM chip

Real information (data or code) – There is a maximum of 16 bytes in this part. The loader places this information into successive memory locations of ROM Single byte – this last byte is the checksum byte of everything in that line HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

Both timers 0 and 1 use the same register, called TMOD (timer mode), to set the various timer operation modes TMOD is a 8-bit register
The lower 4 bits are for Timer 0 The upper 4 bits are for Timer 1 In each case,
The lower 2 bits are used to set the timer mode The upper 2 bits to specify the operation
(MSB) GATE C/T M1 M0 GATE C/T M1 (LSB) M0

If C/T = 0, it is used Example 9-2 as a timer for time delay generation. Find the timer’s clock frequency and its period for various 8051-based system, The clock source for with the crystal frequency 11.0592 MHz when C/T bit of TMOD is 0. the time delay is the Solution: crystal frequency of XTAL ÷12 the 8051
oscillator 1/12 × 11.0529 MHz = 921.6 MHz; T = 1/921.6 kHz = 1.085 us

Timers of 8051 do starting and stopping by either software or hardware control
In using software to start and stop the timer where GATE=0
The start and stop of the timer are controlled by way of software by the TR (timer start) bits TR0 and TR1 – The SETB instruction starts it, and it is stopped by the CLR instruction – These instructions start and stop the timers as long as GATE=0 in the TMOD register

TMOD Register
GATE

• Timer 0, mode 2 • C/T = 0 to use XTAL clock source Find the value for TMOD if we want to program timer 0 in mode 2, • gate = 0 to use use 8051 XTAL for the clock source, and use instructions to start internal (software) start and stop the timer. and stop method. TMOD = 0000 0010

The hardware way of starting and stopping the timer by an external source is achieved by making GATE=1 in the TMOD register

It is a 16-bit timer; therefore, it allows value of 0000 to FFFFH to be loaded into the timer’s register TL and TH After TH and TL are loaded with a 16-bit initial value, the timer must be started
This is done by SETB TR0 for timer 0 and SETB TR1 for timer 1

3.

After the timer is started, it starts to count up
It counts up until it reaches its limit of FFFFH

(cont’) When it rolls over from FFFFH to 0000, it sets high a flag bit called TF (timer flag) – Each timer has its own timer flag: TF0 for timer 0, and TF1 for timer 1 – This timer flag can be monitored When this timer flag is raised, one option would be to stop the timer with the instructions CLR TR0 or CLR TR1, for timer 0 and timer 1, respectively

After the timer reaches its limit and rolls over, in order to repeat the process
TH and TL must be reloaded with the original value, and TF must be reloaded to 0

Load the TMOD value register indicating which timer (timer 0 or timer 1) is to be used and which timer mode (0 or 1) is selected Load registers TL and TH with initial count value Start the timer Keep monitoring the timer flag (TF) with the JNB TFx,target instruction to see if it is raised
Get out of the loop when TF becomes high

5. 6. 7.

Stop the timer Clear the TF flag for the next round Go back to Step 2 to load TH and TL again
10

4. The DELAY subroutine using the timer is called. 5. In the DELAY subroutine, timer 0 is started by the SETB TR0 instruction. 6. Timer 0 counts up with the passing of each clock, which is provided by the crystal oscillator. As the timer counts up, it goes through the states of FFF3, FFF4, FFF5, FFF6, FFF7, FFF8, FFF9, FFFA, FFFB, and so on until it reaches FFFFH. One more clock rolls it to 0, raising the timer flag (TF0=1). At that point, the JNB instruction falls through.
FFF2 TF=0 FFF3 TF=0 FFF4 TF=0 FFFF TF=0 0000 TF=1

7. Timer 0 is stopped by the instruction CLR TR0. The DELAY subroutine ends, and the process is repeated. Notice that to repeat the process, we must reload the TL and TH registers, and start the process is repeated …

Example 9-5 In Example 9-4, calculate the amount of time delay in the DELAY subroutine generated by the timer. Assume XTAL = 11.0592 MHz. Solution: The timer works with a clock frequency of 1/12 of the XTAL frequency; therefore, we have 11.0592 MHz / 12 = 921.6 kHz as the timer frequency. As a result, each clock has a period of T = 1/921.6kHz = 1.085us. In other words, Timer 0 counts up each 1.085 us resulting in delay = number of counts × 1.085us. The number of counts for the roll over is FFFFH – FFF2H = 0DH (13 decimal). However, we add one to 13 because of the extra clock needed when it rolls over from FFFF to 0 and raise the TF flag. This gives 14 × 1.085us = 15.19us for half the pulse. For the entire period it is T = 2 × 15.19us = 30.38us as the time delay generated by the timer.
(a) in hex (FFFF – YYXX + 1) × 1.085 us, where YYXX are TH, TL initial values respectively. Notice that value YYXX are in hex. (b) in decimal Convert YYXX values of the TH, TL register to decimal to get a NNNNN decimal, then (65536 - NNNN) × 1.085 us

Example 9-6 In Example 9-5, calculate the frequency of the square wave generated on pin P1.5. Solution: In the timer delay calculation of Example 9-5, we did not include the overhead due to instruction in the loop. To get a more accurate timing, we need to add clock cycles due to this instructions in the loop. To do that, we use the machine cycle from Table A-1 in Appendix A, as shown below. Cycles HERE: MOV TL0,#0F2H 2 MOV TH0,#0FFH 2 CPL P1.5 1 ACALL DELAY 2 SJMP HERE 2 DELAY: SETB TR0 1 AGAIN: JNB TF0,AGAIN 14 CLR TR0 1 CLR TF0 1 RET 2 Total 28 T = 2 × 28 × 1.085 us = 60.76 us and F = 16458.2 Hz
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
14

Mode 1 Programming
Steps to Mode 1 Program (cont’)

HANEL

PROGRAMMING TIMERS

Example 9-7 Find the delay generated by timer 0 in the following code, using both of the Methods of Figure 9-4. Do not include the overhead due to instruction. CLR P2.3 ;Clear P2.3 MOV TMOD,#01 ;Timer 0, 16-bitmode HERE: MOV TL0,#3EH ;TL0=3Eh, the low byte MOV TH0,#0B8H ;TH0=B8H, the high byte SETB P2.3 ;SET high timer 0 SETB TR0 ;Start the timer 0 AGAIN: JNB TF0,AGAIN ;Monitor timer flag 0 CLR TR0 ;Stop the timer 0 CLR TF0 ;Clear TF0 for next round CLR P2.3 Solution: (a) (FFFFH – B83E + 1) = 47C2H = 18370 in decimal and 18370 × 1.085 us = 19.93145 ms (b) Since TH – TL = B83EH = 47166 (in decimal) we have 65536 – 47166 = 18370. This means that the timer counts from B38EH to FFFF. This plus Rolling over to 0 goes through a total of 18370 clock cycles, where each clock is 1.085 us in duration. Therefore, we have 18370 × 1.085 us = 19.93145 ms as the width of the pulse.
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
15

Mode 1 Programming
Steps to Mode 1 Program (cont’)

HANEL

PROGRAMMING TIMERS

Example 9-8 Modify TL and TH in Example 9-7 to get the largest time delay possible. Find the delay in ms. In your calculation, exclude the overhead due to the instructions in the loop. Solution: To get the largest delay we make TL and TH both 0. This will count up from 0000 to FFFFH and then roll over to zero. CLR MOV HERE: MOV MOV SETB SETB AGAIN: JNB CLR CLR CLR P2.3 ;Clear P2.3 TMOD,#01 ;Timer 0, 16-bitmode TL0,#0 ;TL0=0, the low byte TH0,#0 ;TH0=0, the high byte P2.3 ;SET high P2.3 TR0 ;Start timer 0 TF0,AGAIN ;Monitor timer flag 0 TR0 ;Stop the timer 0 TF0 ;Clear timer 0 flag P2.3

Mode 1 Programming
Steps to Mode 1 Program (cont’)

Making TH and TL both zero means that the timer will count from 0000 to FFFF, and then roll over to raise the TF flag. As a result, it goes through a total Of 65536 states. Therefore, we have delay = (65536 - 0) × 1.085 us = 71.1065ms. HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

16

PROGRAMMING TIMERS

Example 9-9 The following program generates a square wave on P1.5 continuously using timer 1 for a time delay. Find the frequency of the square wave if XTAL = 11.0592 MHz. In your calculation do not include the overhead due to Instructions in the loop. MOV AGAIN: MOV MOV SETB BACK: JNB CLR CPL CLR SJMP TMOD,#10;Timer 1, mod 1 (16-bitmode) TL1,#34H ;TL1=34H, low byte of timer TH1,#76H ;TH1=76H, high byte timer TR1 ;start the timer 1 TF1,BACK ;till timer rolls over TR1 ;stop the timer 1 P1.5 ;comp. p1. to get hi, lo TF1 ;clear timer flag 1 AGAIN ;is not auto-reload

Mode 1 Programming
Steps to Mode 1 Program (cont’)

Solution: Since FFFFH – 7634H = 89CBH + 1 = 89CCH and 89CCH = 35276 clock count and 35276 × 1.085 us = 38.274 ms for half of the square wave. The frequency = 13.064Hz. Also notice that the high portion and low portion of the square wave pulse are equal. In the above calculation, the overhead due to all the instruction in the loop is not included. HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

17

PROGRAMMING TIMERS

To calculate the values to be loaded into the TL and TH registers, look at the following example
Assume XTAL = 11.0592 MHz, we can use the following steps for finding the TH, TL registers’ values
1. Divide the desired time delay by 1.085 us 2. Perform 65536 – n, where n is the decimal value we got in Step1 3. Convert the result of Step2 to hex, where yyxx is the initial hex value to be loaded into the timer’s register 4. Set TL = xx and TH = yy

Example 9-10 Assume that XTAL = 11.0592 MHz. What value do we need to load the timer’s register if we want to have a time delay of 5 ms (milliseconds)? Show the program for timer 0 to create a pulse width of 5 ms on P2.3. Solution: Since XTAL = 11.0592 MHz, the counter counts up every 1.085 us. This means that out of many 1.085 us intervals we must make a 5 ms pulse. To get that, we divide one by the other. We need 5 ms / 1.085 us = 4608 clocks. To Achieve that we need to load into TL and TH the value 65536 – 4608 = EE00H. Therefore, we have TH = EE and TL = 00. CLR MOV HERE: MOV MOV SETB SETB AGAIN: JNB CLR CLR P2.3 ;Clear P2.3 TMOD,#01 ;Timer 0, 16-bitmode TL0,#0 ;TL0=0, the low byte TH0,#0EEH ;TH0=EE, the high byte P2.3 ;SET high P2.3 TR0 ;Start timer 0 TF0,AGAIN ;Monitor timer flag 0 TR0 ;Stop the timer 0 TF0 ;Clear timer 0 flag

It is an 8-bit timer; therefore, it allows only values of 00 to FFH to be loaded into the timer’s register TH After TH is loaded with the 8-bit value, the 8051 gives a copy of it to TL
Then the timer must be started This is done by the instruction SETB TR0 for timer 0 and SETB TR1 for timer 1

3.

After the timer is started, it starts to count up by incrementing the TL register
It counts up until it reaches its limit of FFH When it rolls over from FFH to 00, it sets high the TF (timer flag)

When the TL register rolls from FFH to 0 and TF is set to 1, TL is reloaded automatically with the original value kept by the TH register
To repeat the process, we must simply clear TF and let it go without any need by the programmer to reload the original value This makes mode 2 an auto-reload, in contrast with mode 1 in which the programmer has to reload TH and TL

Load the TMOD value register indicating which timer (timer 0 or timer 1) is to be used, and the timer mode (mode 2) is selected Load the TH registers with the initial count value Start timer Keep monitoring the timer flag (TF) with the JNB TFx,target instruction to see whether it is raised
Get out of the loop when TF goes high

Solution: First notice the target address of SJMP. In mode 2 we do not need to reload TH since it is auto-reload. Now (256 - 05) × 1.085 us = 251 × 1.085 us = 272.33 us is the high portion of the pulse. Since it is a 50% duty cycle square wave, the period T is twice that; as a result T = 2 × 272.33 us = 544.67 us and the frequency = 1.83597 kHz

Solution: Steps to Mode 2 You can use the Windows scientific calculator to verify the result Program provided by the assembler. In Windows calculator, select decimal and enter 200. Then select hex, then +/- to get the TH (cont’) value. Remember that we only use the right two digits and ignore the rest since our data is an 8-bit data. Decimal 2’s complement (TH value) -3 FDH -12 F4H The advantage of using The number 200 is the negative values is that you -48 D0H timer count till the TF don’t need to calculate the -60 C4H is set to 1 value loaded to THx -200 38H HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

28

COUNTER PROGRAMMING

Timers can also be used as counters counting events happening outside the 8051
When it is used as a counter, it is a pulse outside of the 8051 that increments the TH, TL registers TMOD and TH, TL registers are the same as for the timer discussed previously

Programming the timer in the last section also applies to programming it as a counter
Except the source of the frequency

The C/T bit in the TMOD registers decides the source of the clock for the timer
When C/T = 1, the timer is used as a counter and gets its pulses from outside the 8051
The counter counts up as pulses are fed from pins 14 and 15, these pins are called T0 (timer 0 input) and T1 (timer 1 input)
Port 3 pins used for Timers 0 and 1
Pin 14 15 Port Pin P3.4 P3.5 Function T0 T1 Description Timer/counter 0 external input Timer/counter 1 external input

Example 9-18 Assuming that clock pulses are fed into pin T1, write a program for counter 1 in mode 2 to count the pulses and display the state of the TL1 count on P2, which connects to 8 LEDs. Solution: MOV MOV SETB AGAIN: SETB BACK: MOV MOV JNB CLR CLR SJMP

Notice in the above program the role of the instruction SETB P3.5. Since ports are set up for output when the 8051 is powered up, we make P3.5 an input port by making it high. In other words, we must configure (set high) the T1 pin (pin P3.5) to allow pulses to be fed into it. HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

If GATE = 1, the start and stop of the timer are done externally through pins P3.2 and P3.3 for timers 0 and 1, respectively
This hardware way allows to start or stop the timer externally at any time via a simple switch
XTAL oscillator

To speed up the 8051, many recent versions of the 8051 have reduced the number of clocks per machine cycle from 12 to four, or even one The frequency for the timer is always 1/12th the frequency of the crystal attached to the 8051, regardless of the 8051 version

Example 9-26 Assume that a 1-Hz external clock is being fed into pin T1 (P3.5). Write a C program for counter 1 in mode 2 (8-bit auto reload) to count up and display the state of the TL1 count on P1. Start the count at 0H. Solution: #include <reg51.h> sbit T1=P3^5; void main(void){ T1=1; TMOD=0x60; TH1=0; while (1) { do { TR1=1; P1=TL1; } while (TF1==0); TR1=0; TF1=0; } }
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

HANEL

44

PROGRAMMING TIMERS IN C C Programming of Timers as Counters
(cont’)

Example 9-27 Assume that a 1-Hz external clock is being fed into pin T0 (P3.4). Write a C program for counter 0 in mode 1 (16-bit) to count the pulses and display the state of the TH0 and TL0 registers on P2 and P1, respectively. Solution: #include <reg51.h> void main(void){ T0=1; TMOD=0x05; TL0=0 TH0=0; while (1) { do { TR0=1; P1=TL0; P2=TH0; } while (TF0==0); TR0=0; TF0=0; } }
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

HANEL

45

SERIAL COMMUNICATION

Chung-Ping Young 楊中平
Home Automation, Networking, and Entertainment Lab

Dept. of Computer Science and Information Engineering National Cheng Kung University

BASICS OF SERIAL COMMUNICATION

Computers transfer data in two ways:
Parallel
Often 8 or more lines (wire conductors) are used to transfer data to a device that is only a few feet away

Serial
To transfer to a device located many meters away, the serial method is used The data is sent one bit at a time
Serial Transfer Parallel Transfer
D0

Sender

Receiver

Sender
D7

Receiver

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

2

BASICS OF SERIAL COMMUNICATION
(cont’)

At the transmitting end, the byte of data must be converted to serial bits using parallel-in-serial-out shift register At the receiving end, there is a serialin-parallel-out shift register to receive the serial data and pack them into byte When the distance is short, the digital signal can be transferred as it is on a simple wire and requires no modulation If data is to be transferred on the telephone line, it must be converted from 0s and 1s to audio tones
This conversion is performed by a device called a modem, “Modulator/demodulator”

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

3

BASICS OF SERIAL COMMUNICATION
(cont’)

Serial data communication uses two methods
Synchronous method transfers a block of
data at a time byte at a time

Asynchronous method transfers a single

It is possible to write software to use either of these methods, but the programs can be tedious and long
There are special IC chips made by many manufacturers for serial communications
UART (universal asynchronous Receivertransmitter) USART (universal synchronous-asynchronous Receiver-transmitter)
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University

4

BASICS OF SERIAL COMMUNICATION Half- and FullDuplex Transmission

If data can be transmitted and received, it is a duplex transmission
If data transmitted one way a time, it is referred to as half duplex If data can go both ways at a time, it is full

Department of Computer Science and Information Engineering National Cheng Kung University

5

BASICS OF SERIAL COMMUNICATION Start and Stop Bits

A protocol is a set of rules agreed by both the sender and receiver on
How the data is packed How many bits constitute a character When the data begins and ends

Asynchronous serial data communication is widely used for character-oriented transmissions

Each character is placed in between start and stop bits, this is called framing Block-oriented data transfers use the synchronous method

The start bit is always one bit, but the stop bit can be one or two bits
Department of Computer Science and Information Engineering National Cheng Kung University

HANEL

6

BASICS OF SERIAL COMMUNICATION Start and Stop Bits
(cont’)

The start bit is always a 0 (low) and the stop bit(s) is 1 (high)
ASCII character “A” (8-bit binary 0100 0001)

Space

Stop Bit

0

1

0

0

0

0

0

1

Start Mark Bit

D7

D0

Goes out last

Goes out first

The 0 (low) is referred to as space

The transmission begins with a start bit followed by D0, the LSB, then the rest of the bits until MSB (D7), and finally, the one stop bit indicating the end of the character

When there is no transfer, the signal is 1 (high), which is referred to as mark

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

7

BASICS OF SERIAL COMMUNICATION Start and Stop Bits
(cont’)

Due to the extended ASCII characters, 8-bit ASCII data is common In modern PCs the use of one stop bit is standard

In older systems, ASCII characters were 7bit

In older systems, due to the slowness of the receiving mechanical device, two stop bits were used to give the device sufficient time to organize itself before transmission of the next byte

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

8

BASICS OF SERIAL COMMUNICATION Start and Stop Bits
(cont’)

Assuming that we are transferring a text file of ASCII characters using 1 stop bit, we have a total of 10 bits for each character
This gives 25% overhead, i.e. each 8-bit character with an extra 2 bits

In some systems in order to maintain data integrity, the parity bit of the character byte is included in the data frame
UART chips allow programming of the parity bit for odd-, even-, and no-parity options

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

9

BASICS OF SERIAL COMMUNICATION Data Transfer Rate

The rate of data transfer in serial data communication is stated in bps (bits per second) Another widely used terminology for bps is baud rate
It is modem terminology and is defined as the number of signal changes per second In modems, there are occasions when a single change of signal transfers several bits of data

As far as the conductor wire is concerned, the baud rate and bps are the same, and we use the terms interchangeably

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

10

BASICS OF SERIAL COMMUNICATION Data Transfer Rate
(cont’)

The data transfer rate of given computer system depends on communication ports incorporated into that system

IBM PC/XT could transfer data at the rate of 100 to 9600 bps Pentium-based PCs transfer data at rates as high as 56K bps In asynchronous serial data communication, the baud rate is limited to 100K bps

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

11

BASICS OF SERIAL COMMUNICATION RS232 Standards

An interfacing standard RS232 was set by the Electronics Industries Association (EIA) in 1960 The standard was set long before the advent of the TTL logic family, its input and output voltage levels are not TTL compatible
In RS232, a 1 is represented by -3 ~ -25 V, while a 0 bit is +3 ~ +25 V, making -3 to +3 undefined

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

When terminal is turned on, it sends out signal DTR to indicate that it is ready for communication When DCE is turned on and has gone through the self-test, it assert DSR to indicate that it is ready to communicate When the DTE device has byte to transmit, it assert RTS to signal the modem that it has a byte of data to transmit When the modem has room for storing the data it is to receive, it sends out signal CTS to DTE to indicate that it can receive the data now
16

DSR (data set ready)

RTS (request to send)

CTS (clear to send)

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

BASICS OF SERIAL COMMUNICATION RS232 Pins
(cont’)

DCD (data carrier detect)

The modem asserts signal DCD to inform the DTE that a valid carrier has been detected and that contact between it and the other modem is established An output from the modem and an input to a PC indicates that the telephone is ringing It goes on and off in synchronous with the ringing sound

RI (ring indicator)

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

17

8051 CONNECTION TO RS232

A line driver such as the MAX232 chip is required to convert RS232 voltage levels to TTL levels, and vice versa 8051 has two pins that are used specifically for transferring and receiving data serially

These two pins are called TxD and RxD and are part of the port 3 group (P3.0 and P3.1) These pins are TTL compatible; therefore, they require a line driver to make them RS232 compatible

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

18

8051 CONNECTION TO RS232 MAX232
+ C1 + C2

We need a line driver (voltage converter) to convert the R232’s signals to TTL voltage levels that will be acceptable to 8051’s TxD and RxD pins
Vcc 16 1 3 4 5

MAX232

2

C3 +

MAX232 requires four capacitors
8051 MAX232
P3.1 TxD 11 11 14 2 5

6

C4 +

T1in
11 12 10 9

T1out R1in T2out R2int

14 13 7 8 P3.0 10 RxD 12

R1out T2in R2out

13

3

DB-9

TTL side

15

RS232 side

MAX232 has two sets of line drivers

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

19

8051 CONNECTION TO RS232 MAX233

To save board space, some designers use MAX233 chip from Maxim

MAX233 performs the same job as MAX232 but eliminates the need for capacitors Notice that MAX233 and MAX232 are not pin compatible
Vcc 7

13 14 12 17

MAX233

11 15 16 10

8051 MAX233
P3.1 TxD 5 4 18 19 P3.0 10 RxD 3 11 2 5 2 5

T1in
2 3 1 20

T1out R1in T2out R2int

R1out T2in R2out

4

3

DB-9

TTL side

6

9

RS232 side

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

20

SERIAL COMMUNICATION PROGRAMMING

To allow data transfer between the PC and an 8051 system without any error, we must make sure that the baud rate of 8051 system matches the baud rate of the PC’s COM port Hyperterminal function supports baud rates much higher than listed below
PC Baud Rates
110 150 300 600 1200 2400 4800 9600 19200 Baud rates supported by 486/Pentium IBM PC BIOS
21

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

TF is set to 1 every 12 ticks, so it functions as a frequency divider HANEL

9600 4800 2400 1200

Department of Computer Science and Information Engineering National Cheng Kung University

22

SERIAL COMMUNICATION PROGRAMMING SBUF Register

SBUF is an 8-bit register used solely for serial communication
For a byte data to be transferred via the TxD line, it must be placed in the SBUF register

SBUF holds the byte of data when it is received by 8051 RxD line

The moment a byte is written into SBUF, it is framed with the start and stop bits and transferred serially via the TxD line

When the bits are received serially via RxD, the 8051 deframes it by eliminating the stop and start bits, making a byte out of the data received, and then placing it in SBUF
;load SBUF=44h, ASCII for ‘D’ ;copy accumulator into SBUF ;copy SBUF into accumulator

MOV SBUF,#’D’ MOV SBUF,A MOV A,SBUF

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

Serial port mode specifier Serial port mode specifier Used for multiprocessor communication Set/cleared by software to enable/disable reception Not widely used Not widely used Transmit interrupt flag. Set by HW at the begin of the stop bit mode 1. And cleared by SW Receive interrupt flag. Set by HW at the begin of the stop bit mode 1. And cleared by SW

Note:

Make SM2, TB8, and RB8 =0

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

When it is high, it allows 8051 to receive data on RxD pin If low, the receiver is disable

TI (transmit interrupt)

When 8051 finishes the transfer of 8-bit character

It raises TI flag to indicate that it is ready to transfer another byte TI bit is raised at the beginning of the stop bit

RI (receive interrupt)

When 8051 receives data serially via RxD, it gets rid of the start and stop bits and places the byte in SBUF register
It raises the RI flag bit to indicate that a byte has been received and should be picked up before it is lost RI is raised halfway through the stop bit

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

26

SERIAL COMMUNICATION PROGRAMMING Programming Serial Data Transmitting

In programming the 8051 to transfer character bytes serially
1.

2. 3.

4. 5. 6. 7.

8. HANEL

TMOD register is loaded with the value 20H, indicating the use of timer 1 in mode 2 (8-bit auto-reload) to set baud rate The TH1 is loaded with one of the values to set baud rate for serial data transfer The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8bit data is framed with start and stop bits TR1 is set to 1 to start timer 1 TI is cleared by CLR TI instruction The character byte to be transferred serially is written into SBUF register The TI flag bit is monitored with the use of instruction JNB TI,xx to see if the character has been transferred completely To transfer the next byte, go to step 5
27

Department of Computer Science and Information Engineering National Cheng Kung University

Department of Computer Science and Information Engineering National Cheng Kung University

29

SERIAL COMMUNICATION PROGRAMMING Importance of TI Flag

The steps that 8051 goes through in transmitting a character via TxD
1. 2. 3. 4.

The byte character to be transmitted is written into the SBUF register The start bit is transferred The 8-bit character is transferred on bit at a time The stop bit is transferred By monitoring the TI flag, we make sure that we are not overloading the SBUF
It is during the transfer of the stop bit that 8051 raises the TI flag, indicating that the last character was transmitted If we write another byte into the SBUF before TI is raised, the untransmitted portion of the previous byte will be lost

5.

6.

After SBUF is loaded with a new byte, the TI flag bit must be forced to 0 by CLR TI in order for this new byte to be transferred
30

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

SERIAL COMMUNICATION PROGRAMMING Importance of TI Flag
(cont’)

By checking the TI flag bit, we know whether or not the 8051 is ready to transfer another byte
It must be noted that TI flag bit is raised by 8051 itself when it finishes data transfer It must be cleared by the programmer with instruction CLR TI If we write a byte into SBUF before the TI flag bit is raised, we risk the loss of a portion of the byte being transferred

The TI bit can be checked by
The instruction JNB TI,xx Using an interrupt

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

31

SERIAL COMMUNICATION PROGRAMMING Programming Serial Data Receiving

In programming the 8051 to receive character bytes serially
1.

2. 3.

4. 5. 6.

7. 8. HANEL

TMOD register is loaded with the value 20H, indicating the use of timer 1 in mode 2 (8-bit auto-reload) to set baud rate TH1 is loaded to set baud rate The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8bit data is framed with start and stop bits TR1 is set to 1 to start timer 1 RI is cleared by CLR RI instruction The RI flag bit is monitored with the use of instruction JNB RI,xx to see if an entire character has been received yet When RI is raised, SBUF has the byte, its contents are moved into a safe place To receive the next character, go to step 5
32

Department of Computer Science and Information Engineering National Cheng Kung University

Example 10-5 Assume that the 8051 serial port is connected to the COM port of IBM PC, and on the PC, we are using the terminal.exe program to send and receive data serially. P1 and P2 of the 8051 are connected to LEDs and switches, respectively. Write an 8051 program to (a) send to PC the message “We Are Ready”, (b) receive any data send by PC and put it on LEDs connected to P1, and (c) get data on switches connected to P2 and send it to PC serially. The program should perform part (a) once, but parts (b) and (c) continuously, use 4800 baud rate. Solution:
ORG MOV MOV MOV MOV SETB MOV CLR MOV 0 P2,#0FFH ;make P2 an input port TMOD,#20H ;timer 1, mode 2 TH1,#0FAH ;4800 baud rate SCON,#50H ;8-bit, 1 stop, REN enabled TR1 ;start timer 1 DPTR,#MYDATA ;load pointer for message A A,@A+DPTR ;get the character

H_1: ...

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

Department of Computer Science and Information Engineering National Cheng Kung University

36

SERIAL COMMUNICATION PROGRAMMING Importance of RI Flag

In receiving bit via its RxD pin, 8051 goes through the following steps
1.

It receives the start bit
Indicating that the next bit is the first bit of the character byte it is about to receive

2. 3.

The 8-bit character is received one bit at time The stop bit is received
When receiving the stop bit 8051 makes RI = 1, indicating that an entire character byte has been received and must be picked up before it gets overwritten by an incoming character

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

37

(cont’)

SERIAL COMMUNICATION PROGRAMMING Importance of RI Flag
(cont’)

4.

By checking the RI flag bit when it is raised, we know that a character has been received and is sitting in the SBUF register
We copy the SBUF contents to a safe place in some other register or memory before it is lost

5.

After the SBUF contents are copied into a safe place, the RI flag bit must be forced to 0 by CLR RI in order to allow the next received character byte to be placed in SBUF
Failure to do this causes loss of the received character

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

38

SERIAL COMMUNICATION PROGRAMMING Importance of RI Flag
(cont’)

By checking the RI flag bit, we know whether or not the 8051 received a character byte

If we failed to copy SBUF into a safe place, we risk the loss of the received byte It must be noted that RI flag bit is raised by 8051 when it finish receive data It must be cleared by the programmer with instruction CLR RI If we copy SBUF into a safe place before the RI flag bit is raised, we risk copying garbage The instruction JNB RI,xx Using an interrupt

The RI bit can be checked by

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

39

SERIAL COMMUNICATION PROGRAMMING Doubling Baud Rate

There are two ways to increase the The system baud rate of data transfer crystal is fixed
To use a higher frequency crystal To change a bit in the PCON register

PCON register is an 8-bit register
When 8051 is powered up, SMOD is zero We can set it to high by software and thereby double the baud rate
SMOD ---GF1 GF0 PD IDL

It is not a bitaddressable register

MOV A,PCON SETB ACC.7 MOV PCON,A

;place a copy of PCON in ACC ;make D7=1 ;changing any other bits

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

Example 10-8 Find the baud rate if TH1 = -2, SMOD = 1, and XTAL = 11.0592 MHz. Is this baud rate supported by IBM compatible PCs? Solution: With XTAL = 11.0592 and SMOD = 1, we have timer frequency = 57,600 Hz. The baud rate is 57,600/2 = 28,800. This baud rate is not supported by the BIOS of the PCs; however, the PC can be programmed to do data transfer at such a speed. Also, HyperTerminal in Windows supports this and other baud rates.

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

Department of Computer Science and Information Engineering National Cheng Kung University

46

PROGRAMMING THE SECOND SERIAL PORT

Many new generations of 8051 microcontroller come with two serial ports, like DS89C4x0 and DS80C320
The second serial port of DS89C4x0 uses pins P1.2 and P1.3 for the Rx and Tx lines The second serial port uses some reserved SFR addresses for the SCON and SBUF
There is no universal agreement among the makers as to which addresses should be used – The SFR addresses of C0H and C1H are set aside for SBUF and SCON of DS89C4x0 The DS89C4x0 technical documentation refers to these registers as SCON1 and SBUF1 The first ones are designated as SCON0 and SBUF0

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

Department of Computer Science and Information Engineering National Cheng Kung University

49

PROGRAMMING THE SECOND SERIAL PORT
(cont’)

Upon reset, DS89c4x0 uses Timer 1 for setting baud rate of both serial ports
While each serial port has its own SCON and SBUF registers, both ports can use Timer1 for setting the baud rate SBUF and SCON refer to the SFR registers of the first serial port
Since the older 8051 assemblers do not support this new second serial port, we need to define them in program To avoid confusion, in DS89C4x0 programs we use SCON0 and SBUF0 for the first and SCON1 and SBUF1for the second serial ports

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

An interrupt is an external or internal event that interrupts the microcontroller to inform it that a device needs its service A single microcontroller can serve several devices by two ways
Interrupts
Whenever any device needs its service, the device notifies the microcontroller by sending it an interrupt signal Upon receiving an interrupt signal, the microcontroller interrupts whatever it is doing and serves the device The program which is associated with the interrupt is called the interrupt service routine (ISR) or interrupt handler

Polling
The microcontroller continuously monitors the status of a given device When the conditions met, it performs the service After that, it moves on to monitor the next device until every one is serviced

Polling can monitor the status of several devices and serve each of them as certain conditions are met
The polling method is not efficient, since it wastes much of the microcontroller’s time by polling devices that do not need service ex. JNB TF,target
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

3

INTERRUPTS Interrupts vs. Polling
(cont’)

The advantage of interrupts is that the microcontroller can serve many devices (not all at the same time)
Each devices can get the attention of the microcontroller based on the assigned priority For the polling method, it is not possible to assign priority since it checks all devices in a round-robin fashion

The microcontroller can also ignore (mask) a device request for service
This is not possible for the polling method

For every interrupt, there must be an interrupt service routine (ISR), or interrupt handler
When an interrupt is invoked, the microcontroller runs the interrupt service routine For every interrupt, there is a fixed location in memory that holds the address of its ISR The group of memory locations set aside to hold the addresses of ISRs is called interrupt vector table

Upon activation of an interrupt, the microcontroller goes through the following steps
1.

2. 3.

It finishes the instruction it is executing and saves the address of the next instruction (PC) on the stack It also saves the current status of all the interrupts internally (i.e: not on the stack) It jumps to a fixed location in memory, called the interrupt vector table, that holds the address of the ISR

The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it
It starts to execute the interrupt service subroutine until it reaches the last instruction of the subroutine which is RETI (return from interrupt)

5.

Upon executing the RETI instruction, the microcontroller returns to the place where it was interrupted
First, it gets the program counter (PC) address from the stack by popping the top two bytes of the stack into the PC Then it starts to execute from that address

Six interrupts are allocated as follows
Reset – power-up reset Two interrupts are set aside for the timers: one for timer 0 and one for timer 1 Two interrupts are set aside for hardware external interrupts
P3.2 and P3.3 are for the external hardware interrupts INT0 (or EX1), and INT1 (or EX2)

Serial communication has a single interrupt that belongs to both receive and transfer

ORG 0 ;wake-up ROM reset location LJMP MAIN ;by-pass int. vector table ;---- the wake-up program ORG 30H Only three bytes of ROM space MAIN: assigned to the reset pin. We put .... the LJMP as the first instruction END and redirect the processor away
from the interrupt vector table.

Upon reset, all interrupts are disabled (masked), meaning that none will be responded to by the microcontroller if they are activated The interrupts must be enabled by software in order for the microcontroller to respond to them
There is a register called IE (interrupt enable) that is responsible for enabling (unmasking) and disabling (masking) the interrupts

Bit D7 of the IE register (EA) must be set to high to allow the rest of register to take effect The value of EA
If EA = 1, interrupts are enabled and will be responded to if their corresponding bits in IE are high If EA = 0, no interrupt will be responded to, even if the associated bit in the IE register is high

The timer flag (TF) is raised when the timer rolls over
In polling TF, we have to wait until the TF is raised
The problem with this method is that the microcontroller is tied down while waiting for TF to be raised, and can not do anything else

Using interrupts solves this problem and, avoids tying down the controller
If the timer interrupt in the IE register is enabled, whenever the timer rolls over, TF is raised, and the microcontroller is interrupted in whatever it is doing, and jumps to the interrupt vector table to service the ISR In this way, the microcontroller can do other until it is notified that the timer has rolled over
TF0 Timer 0 Interrupt Vector
Jumps to

Example 11-3 Rewrite Example 11-2 to create a square wave that has a high portion of 1085 us and a low portion of 15 us. Assume XTAL=11.0592MHz. Use timer 1. Solution:
Since 1085 us is 1000 × 1.085 we need to use mode 1 of timer 1.

The 8051 has two external hardware interrupts
Pin 12 (P3.2) and pin 13 (P3.3) of the 8051, designated as INT0 and INT1, are used as external hardware interrupts
The interrupt vector table locations 0003H and 0013H are set aside for INT0 and INT1

There are two activation levels for the external hardware interrupts
Level trigged Edge trigged

In the level-triggered mode, INT0 and INT1 pins are normally high
If a low-level signal is applied to them, it triggers the interrupt Then the microcontroller stops whatever it is doing and jumps to the interrupt vector table to service that interrupt The low-level signal at the INT pin must be removed before the execution of the last instruction of the ISR, RETI; otherwise, another interrupt will be generated

This is called a level-triggered or levelactivated interrupt and is the default mode upon reset of the 8051
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

22

EXTERNAL HARDWARE INTERRUPTS Level-Triggered Interrupt
(cont’)

Example 11-5 Assume that the INT1 pin is connected to a switch that is normally high. Whenever it goes low, it should turn on an LED. The LED is connected to P1.3 and is normally off. When it is turned on it should stay on for a fraction of a second. As long as the switch is pressed low, the LED should stay on. Vcc Solution:
ORG 0000H LJMP MAIN ;by-pass interrupt ;vector table ;--ISR for INT1 to turn on LED ORG 0013H ;INT1 ISR SETB P1.3 ;turn on LED MOV R3,#255 BACK: DJNZ R3,BACK ;keep LED on for a CLR P1.3 ;turn off the LED RETI ;return from ISR
INT1 P1.3

Pins P3.2 and P3.3 are used for normal I/O unless the INT0 and INT1 bits in the IE register are enabled
After the hardware interrupts in the IE register are enabled, the controller keeps sampling the INTn pin for a low-level signal once each machine cycle According to one manufacturer’s data sheet,
The pin must be held in a low state until the start of the execution of ISR If the INTn pin is brought back to a logic high before the start of the execution of ISR there will be no interrupt If INTn pin is left at a logic low after the RETI instruction of the ISR, another interrupt will be activated after one instruction is executed
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

To ensure the activation of the hardware interrupt at the INTn pin, make sure that the duration of the low-level signal is around 4 machine cycles, but no more
This is due to the fact that the level-triggered interrupt is not latched Thus the pin must be held in a low state until the start of the ISR execution
1 MC 4 machine cycles 1.085us 4 × 1.085us note: On reset, IT0 (TCON.0) and IT1 (TCON.2) are both low, making external interrupt level-triggered To INT0 or INT1 pins

To make INT0 and INT1 edgetriggered interrupts, we must program the bits of the TCON register
The TCON register holds, among other bits, the IT0 and IT1 flag bits that determine level- or edge-triggered mode of the hardware interrupt
IT0 and IT1 are bits D0 and D2 of the TCON register They are also referred to as TCON.0 and TCON.2 since the TCON register is bitaddressable

Timer 1 overflow flag. Set by hardware when timer/counter 1 overflows. Cleared by hardware as the processor vectors to the interrupt service routine Timer 1 run control bit. Set/cleared by software to turn timer/counter 1 on/off Timer 0 overflow flag. Set by hardware when timer/counter 0 overflows. Cleared by hardware as the processor vectors to the interrupt service routine Timer 0 run control bit. Set/cleared by software to turn timer/counter 0 on/off
27

Assume that pin 3.3 (INT1) is connected to a pulse generator, write a program in which the falling edge of the pulse will send a high to P1.3, which is connected to an LED (or buzzer). In other words, the LED is turned on and off at the same rate as the pulses are applied to the INT1 pin. Solution:

When the falling edge of the signal is applied to pin INT1, the LED will be turned on momentarily.

The on-state duration depends on the time delay inside the ISR for INT1

In edge-triggered interrupts
The external source must be held high for at least one machine cycle, and then held low for at least one machine cycle The falling edge of pins INT0 and INT1 are latched by the 8051 and are held by the TCON.1 and TCON.3 bits of TCON register
Function as interrupt-in-service flags It indicates that the interrupt is being serviced now and on this INTn pin, and no new interrupt will be responded to until this service is finished
Minimum pulse duration to detect edge-triggered interrupts XTAL=11.0592MHz
1 MC 1.085us 1 MC 1.085us

Regarding the IT0 and IT1 bits in the TCON register, the following two points must be emphasized
When the ISRs are finished (that is, upon execution of RETI), these bits (TCON.1 and TCON.3) are cleared, indicating that the interrupt is finished and the 8051 is ready to respond to another interrupt on that pin During the time that the interrupt service routine is being executed, the INTn pin is ignored, no matter how many times it makes a high-to-low transition
RETI clears the corresponding bit in TCON register (TCON.1 or TCON.3) There is no need for instruction CLR TCON.1 before RETI in the ISR associated with INT0

Example 11-7 What is the difference between the RET and RETI instructions? Explain why we can not use RET instead of RETI as the last instruction of an ISR. Solution: Both perform the same actions of popping off the top two bytes of the stack into the program counter, and marking the 8051 return to where it left off. However, RETI also performs an additional task of clearing the interrupt-in-service flag, indicating that the servicing of the interrupt is over and the 8051 now can accept a new interrupt on that pin. If you use RET instead of RETI as the last instruction of the interrupt service routine, you simply block any new interrupt on that pin after the first interrupt, since the pin status would indicate that the interrupt is still being serviced. In the cases of TF0, TF1, TCON.1, and TCON.3, they are cleared due to the execution of RETI.

TI (transfer interrupt) is raised when the last bit of the framed data, the stop bit, is transferred, indicating that the SBUF register is ready to transfer the next byte RI (received interrupt) is raised when the entire frame of data, including the stop bit, is received
In other words, when the SBUF register has a byte, RI is raised to indicate that the received byte needs to be picked up before it is lost (overrun) by new incoming serial data

In the 8051 there is only one interrupt set aside for serial communication
This interrupt is used to both send and receive data If the interrupt bit in the IE register (IE.4) is enabled, when RI or TI is raised the 8051 gets interrupted and jumps to memory location 0023H to execute the ISR In that ISR we must examine the TI and RI flags to see which one caused the interrupt and respond accordingly
TI 0023H RI Serial interrupt is invoked by TI or RI flags

The serial interrupt is used mainly for receiving data and is never used for sending data serially
This is like getting a telephone call in which we need a ring to be notified If we need to make a phone call there are other ways to remind ourselves and there is no need for ringing However in receiving the phone call, we must respond immediately no matter what we are doing or we will miss the call

... ;-----------------SERIAL PORT ISR ORG 100H SERIAL: JB TI,TRANS;jump if TI is high MOV A,SBUF ;otherwise due to receive CLR RI ;clear RI since CPU doesn’t RETI ;return from ISR TRANS: CLR TI ;clear TI since CPU doesn’t RETI ;return from ISR END The moment a byte is written into SBUF it is framed and transferred serially. As a result, when the last bit (stop bit) is transferred the TI is raised, and that causes the serial interrupt to be invoked since the corresponding bit in the IE register is high. In the serial ISR, we check for both TI and RI since both could have invoked interrupt.

Example 11-9 Write a program in which the 8051 gets data from P1 and sends it to P2 continuously while incoming data from the serial port is sent to P0. Assume that XTAL=11.0592. Set the baud rata at 9600. Solution: ORG LJMP ORG LJMP ORG MAIN: MOV MOV MOV MOV MOV SETB BACK: MOV MOV SJMP ...

Example 11-10 Write a program using interrupts to do the following: (a) Receive data serially and sent it to P0, (b) Have P1 port read and transmitted serially, and a copy given to P2, (c) Make timer 0 generate a square wave of 5kHz frequency on P0.1. Assume that XTAL-11,0592. Set the baud rate at 4800. Solution: ORG LJMP ORG CPL RETI ORG LJMP ORG MAIN: MOV MOV MOV MOV MOV ... 0 MAIN 000BH P0.1

When the 8051 is powered up, the priorities are assigned according to the following
In reality, the priority scheme is nothing but an internal polling sequence in which the 8051 polls the interrupts in the sequence listed and responds accordingly
Interrupt Priority Upon Reset Highest To Lowest Priority External Interrupt 0 Timer Interrupt 0 External Interrupt 1 Timer Interrupt 1 Serial Communication (INT0) (TF0) (INT1) (TF1) (RI + TI)
43

Example 11-11 Discuss what happens if interrupts INT0, TF0, and INT1 are activated at the same time. Assume priority levels were set by the power-up reset and the external hardware interrupts are edgetriggered. Solution: If these three interrupts are activated at the same time, they are latched and kept internally. Then the 8051 checks all five interrupts according to the sequence listed in Table 11-3. If any is activated, it services it in sequence. Therefore, when the above three interrupts are activated, IE0 (external interrupt 0) is serviced first, then timer 0 (TF0), and finally IE1 (external interrupt 1).

We can alter the sequence of interrupt priority by assigning a higher priority to any one of the interrupts by programming a register called IP (interrupt priority)
To give a higher priority to any of the interrupts, we make the corresponding bit in the IP register high When two or more interrupt bits in the IP register are set to high
While these interrupts have a higher priority than others, they are serviced according to the sequence of Table 11-13

Example 11-12 (a) Program the IP register to assign the highest priority to INT1(external interrupt 1), then (b) discuss what happens if INT0, INT1, and TF0 are activated at the same time. Assume the interrupts are both edge-triggered. Solution: (a) MOV IP,#00000100B ;IP.2=1 assign INT1 higher priority. The instruction SETB IP.2 also will do the same thing as the above line since IP is bit-addressable. (b) The instruction in Step (a) assigned a higher priority to INT1 than the others; therefore, when INT0, INT1, and TF0 interrupts are activated at the same time, the 8051 services INT1 first, then it services INT0, then TF0. This is due to the fact that INT1 has a higher priority than the other two because of the instruction in Step (a). The instruction in Step (a) makes both the INT0 and TF0 bits in the IP register 0. As a result, the sequence in Table 11-3 is followed which gives a higher priority to INT0 over TF0

Example 11-13 Assume that after reset, the interrupt priority is set the instruction MOV IP,#00001100B. Discuss the sequence in which the interrupts are serviced. Solution: The instruction “MOV IP #00001100B” (B is for binary) and timer 1 (TF1)to a higher priority level compared with the reset of the interrupts. However, since they are polled according to Table, they will have the following priority. Highest Priority External Interrupt 1 Timer Interrupt 1 External Interrupt 0 Timer Interrupt 0 Serial Communication (INT1) (TF1) (INT0) (TF0) (RI+TI)

In the 8051 a low-priority interrupt can be interrupted by a higher-priority interrupt but not by another lowpriority interrupt
Although all the interrupts are latched and kept internally, no low-priority interrupt can get the immediate attention of the CPU until the 8051 has finished servicing the high-priority interrupts

To test an ISR by way of simulation can be done with simple instructions to set the interrupts high and thereby cause the 8051 to jump to the interrupt vector table
ex. If the IE bit for timer 1 is set, an instruction such as SETB TF1 will interrupt the 8051 in whatever it is doing and will force it to jump to the interrupt vector table
We do not need to wait for timer 1 go roll over to have an interrupt

It can assign a register bank to an ISR
This avoids code overhead due to the pushes and pops of the R0 – R7 registers
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

Chung-Ping Young 楊中平
Home Automation, Networking, and Entertainment Lab

Dept. of Computer Science and Information Engineering National Cheng Kung University

SEMICONDUCTOR MEMORY Memory Capacity

The number of bits that a semiconductor memory chip can store is called chip capacity
It can be in units of Kbits (kilobits), Mbits (megabits), and so on

This must be distinguished from the storage capacity of computer systems
While the memory capacity of a memory IC chip is always given bits, the memory capacity of a computer system is given in bytes
16M memory chip – 16 megabits A computer comes with 16M memory – 16 megabytes

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

2

SEMICONDUCTOR MEMORY Memory Organization

Memory chips are organized into a number of locations within the IC
Each location can hold 1 bit, 4 bits, 8 bits, or even 16 bits, depending on how it is designed internally
The number of locations within a memory IC depends on the address pins The number of bits that each location can hold is always equal to the number of data pins

To summarize
A memory chip contain 2x location, where x is the number of address pins Each location contains y bits, where y is the number of data pins on the chip The entire chip will contain 2x × y bits
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University

3

SEMICONDUCTOR MEMORY Speed

One of the most important characteristics of a memory chip is the speed at which its data can be accessed
To access the data, the address is presented to the address pins, the READ pin is activated, and after a certain amount of time has elapsed, the data shows up at the data pins The shorter this elapsed time, the better, and consequently, the more expensive the memory chip The speed of the memory chip is commonly referred to as its access time

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

4

SEMICONDUCTOR MEMORY Speed
(cont’)

Example A given memory chip has 12 address pins and 4 data pins. Find: (a) The organization, and (b) the capacity. Solution: (a) This memory chip has 4096 locations (212 = 4096), and each location can hold 4 bits of data. This gives an organization of 4096 × 4, often represented as 4K × 4. (b) The capacity is equal to 16K bits since there is a total of 4K locations and each location can hold 4 bits of data. Example A 512K memory chip has 8 pins for data. Find: (a) The organization, and (b) the number of address pins for this memory chip. Solution: (a) A memory chip with 8 data pins means that each location within the chip can hold 8 bits of data. To find the number of locations within this memory chip, divide the capacity by the number of data pins. 512K/8 = 64K; therefore, the organization for this memory chip is 64K × 8 (b) The chip has 16 address lines since 216 = 64K

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

5

SEMICONDUCTOR MEMORY ROM (Read-only Memory)

ROM is a type of memory that does not lose its contents when the power is turned off
ROM is also called nonvolatile memory

Department of Computer Science and Information Engineering National Cheng Kung University

6

SEMICONDUCTOR MEMORY ROM
PROM (Programmable ROM)

PROM refers to the kind of ROM that the user can burn information into
PROM is a user-programmable memory For every bit of the PROM, there exists a fuse

If the information burned into PROM is wrong, that PROM must be discarded since its internal fuses are blown permanently
PROM is also referred to as OTP (one-time programmable) Programming ROM, also called burning ROM, requires special equipment called a ROM burner or ROM programmer

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

7

SEMICONDUCTOR MEMORY ROM
EPROM (Erasable Programmable ROM)

EPROM was invented to allow making changes in the contents of PROM after it is burned
In EPROM, one can program the memory chip and erase it thousands of times

A widely used EPROM is called UVEPROM
UV stands for ultra-violet The only problem with UV-EPROM is that erasing its contents can take up to 20 minutes All UV-EPROM chips have a window that is used to shine ultraviolet (UV) radiation to erase its contents
Department of Computer Science and Information Engineering National Cheng Kung University

HANEL

8

SEMICONDUCTOR MEMORY ROM
EPROM (Erasable Programmable ROM) (cont’)

To program a UV-EPROM chip, the following steps must be taken:
Its contents must be erased
To erase a chip, it is removed from its socket on the system board and placed in EPROM erasure equipment to expose it to UV radiation for 15-20 minutes

Program the chip
To program a UV-EPROM chip, place it in the ROM burner To burn code or data into EPROM, the ROM burner uses 12.5 volts, Vpp in the UV-EPROM data sheet or higher, depending on the EPROM type Place the chip back into its system board socket
Department of Computer Science and Information Engineering National Cheng Kung University

HANEL

9

SEMICONDUCTOR MEMORY ROM
EPROM (Erasable Programmable ROM) (cont’)

There is an EPROM programmer (burner), and there is also separate EPROM erasure equipment The major disadvantage of UV-EPROM, is that it cannot be programmed while in the system board Notice the pattern of the IC numbers
Ex. 27128-25 refers to UV-EPROM that has a capacity of 128K bits and access time of 250 nanoseconds

27xx always refers to UV-EPROM chips
For ROM chip 27128, find the number of data and address pins. Solution: The 27128 has a capacity of 128K bits. It has 16K × 8 organization (all ROMs have 8 data pins), which indicates that there are 8 pins for data, and 14 pins for address (214 = 16K)

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

EEPROM has several advantage over EPROM
Its method of erasure is electrical and therefore instant, as opposed to the 20minute erasure time required for UVEPROM One can select which byte to be erased, in contrast to UV-EPROM, in which the entire contents of ROM are erased One can program and erase its contents while it is still in the system board
EEPROM does not require an external erasure and programming device The designer incorporate into the system board the circuitry to program the EEPROM

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

11

SEMICONDUCTOR MEMORY ROM
Flash Memory EPROM

Flash EPROM has become a popular user-programmable memory chip since the early 1990s
The process of erasure of the entire contents takes less than a second, or might say in a flash
The erasure method is electrical It is commonly called flash memory

The major difference between EEPROM and flash memory is
Flash memory’s contents are erased, then the entire device is erased – There are some flash memories are recently made so that the erasure can be done block by block One can erase a desired section or byte on EEPROM

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

12

SEMICONDUCTOR MEMORY ROM
Flash Memory EPROM (cont’)

It is believed that flash memory will replace part of the hard disk as a mass storage medium
The flash memory can be programmed while it is in its socket on the system board
Widely used as a way to upgrade PC BIOS ROM

Flash memory is semiconductor memory with access time in the range of 100 ns compared with disk access time in the range of tens of milliseconds Flash memory’s program/erase cycles must become infinite, like hard disks
Program/erase cycle refers to the number of times that a chip can be erased and programmed before it becomes unusable The program/erase cycle is 100,000 for flash and EEPROM, 1000 for UV-EPROM

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

13

SEMICONDUCTOR MEMORY ROM
Mask ROM

Mask ROM refers to a kind of ROM in which the contents are programmed by the IC manufacturer, not userprogrammable
The terminology mask is used in IC fabrication Since the process is costly, mask ROM is used when the needed volume is high and it is absolutely certain that the contents will not change The main advantage of mask ROM is its cost, since it is significantly cheaper than other kinds of ROM, but if an error in the data/code is found, the entire batch must be thrown away
Department of Computer Science and Information Engineering National Cheng Kung University

HANEL

14

SEMICONDUCTOR MEMORY RAM (Random Access Memory)

RAM memory is called volatile memory since cutting off the power to the IC will result in the loss of data
Sometimes RAM is also referred to as RAWM (read and write memory), in contrast to ROM, which cannot be written to

Department of Computer Science and Information Engineering National Cheng Kung University

15

SEMICONDUCTOR MEMORY RAM
SRAM (Static RAM)

Storage cells in static RAM memory are made of flip-flops and therefore do not require refreshing in order to keep their data The problem with the use of flip-flops for storage cells is that each cell require at least 6 transistors to build, and the cell holds only 1 bit of data
In recent years, the cells have been made of 4 transistors, which still is too many The use of 4-transistor cells plus the use of CMOS technology has given birth to a highcapacity SRAM, but its capacity is far below DRAM

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

16

SEMICONDUCTOR MEMORY RAM
NV-RAM (Nonvolatile RAM)

NV-RAM combines the best of RAM and ROM
The read and write ability of RAM, plus the nonvolatility of ROM

NV-RAM chip internally is made of the following components
It uses extremely power-efficient SRAM cells built out of CMOS It uses an internal lithium battery as a backup energy source It uses an intelligent control circuitry
The main job of this control circuitry is to monitor the Vcc pin constantly to detect loss of the external power supply

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

17

SEMICONDUCTOR MEMORY RAM
Checksum Byte ROM

To ensure the integrity of the ROM contents, every system must perform the checksum calculation
The process of checksum will detect any corruption of the contents of ROM The checksum process uses what is called a checksum byte
The checksum byte is an extra byte that is tagged to the end of series of bytes of data

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

18

SEMICONDUCTOR MEMORY RAM
Checksum Byte ROM (cont’)

To calculate the checksum byte of a series of bytes of data
Add the bytes together and drop the carries Take the 2’s complement of the total sum, and that is the checksum byte, which becomes the last byte of the series

To perform the checksum operation, add all the bytes, including the checksum byte
The result must be zero If it is not zero, one or more bytes of data have been changed

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

19

SEMICONDUCTOR MEMORY RAM
Checksum Byte ROM (cont’)

Assume that we have 4 bytes of hexadecimal data: 25H, 62H, 3FH, and 52H.(a) Find the checksum byte, (b) perform the checksum operation to ensure data integrity, and (c) if the second byte 62H has been changed to 22H, show how checksum detects the error. Solution: (a) Find the checksum byte. 25H The checksum is calculated by first adding the + 62H bytes. The sum is 118H, and dropping the carry, + 3FH we get 18H. The checksum byte is the 2’s + 52H complement of 18H, which is E8H 118H (b) Perform the checksum operation to ensure data integrity. 25H + 62H Adding the series of bytes including the checksum + 3FH byte must result in zero. This indicates that all the + 52H bytes are unchanged and no byte is corrupted. + E8H 200H (dropping the carries) (c) If the second byte 62H has been changed to 22H, show how checksum detects the error. 25H + 22H Adding the series of bytes including the checksum + 3FH byte shows that the result is not zero, which indicates + 52H that one or more bytes have been corrupted. + E8H 1C0H (dropping the carry, we get C0H) Department of Computer Science and Information Engineering National Cheng Kung University

HANEL

20

SEMICONDUCTOR MEMORY RAM
DRAM (Dynamic RAM)

Dynamic RAM uses a capacitor to store each bit
It cuts down the number of transistors needed to build the cell It requires constant refreshing due to leakage

The advantages and disadvantages of DRAM memory
The major advantages are high density (capacity), cheaper cost per bit, and lower power consumption per bit The disadvantages is that
it must be refreshed periodically, due to the fact that the capacitor cell loses its charge; While it is being refreshed, the data cannot be accessed

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

21

SEMICONDUCTOR MEMORY RAM
Packing Issue in DRAM

In DRAM there is a problem of packing a large number of cells into a single chip with the normal number of pins assigned to addresses

Using conventional method of data access, large number of pins defeats the purpose of high density and small packaging
For example, a 64K-bit chip (64K×1) must have 16 address lines and 1 data line, requiring 16 pins to send in the address

The method used is to split the address in half and send in each half of the address through the same pins, thereby requiring fewer address pins
Department of Computer Science and Information Engineering National Cheng Kung University

HANEL

22

SEMICONDUCTOR MEMORY RAM
Packing Issue in DRAM (cont’)

Internally, the DRAM structure is divided into a square of rows and columns The first half of the address is called the row and the second half is called column

The first half of the address is sent in through the address pins, and by activating RAS (row address strobe), the internal latches inside DRAM grab the first half of the address After that, the second half of the address is sent in through the same pins, and by activating CAS (column address strobe), the internal latches inside DRAM latch the second half of the address
23

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

SEMICONDUCTOR MEMORY RAM
DRAM Organization

In the discussion of ROM, we noted that all of them have 8 pins for data
This is not the case for DRAM memory chips, which can have any of the x1, x4, x8, x16 organizations
Discuss the number of pins set aside for address in each of the following memory chips. (a) 16K×4 DRAM (b) 16K×4 SRAM Solution : Since 214 = 16K : (a) For DRAM we have 7 pins (A0-A6) for the address pins and 2 pins for RAS and CAS (b) For SRAM we have 14 pins for address and no pins for RAS and CAS since they are associated only with DRAM. In both cases we have 4 pins for the data bus.

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

24

MEMORY ADDRESS DECODING

The CPU provides the address of the data desired, but it is the job of the decoding circuitry to locate the selected memory block
Memory chips have one or more pins called CS (chip select), which must be activated for the memory’s contents to be accessed Sometimes the chip select is also referred to as chip enable (CE)

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

25

MEMORY ADDRESS DECODING
(cont’)

In connecting a memory chip to the CPU, note the following points
The data bus of the CPU is connected directly to the data pins of the memory chip Control signals RD (read) and WR (memory write) from the CPU are connected to the OE (output enable) and WE (write enable) pins of the memory chip In the case of the address buses, while the lower bits of the address from the CPU go directly to the memory chip address pins, the upper ones are used to activate the CS pin of the memory chip

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

26

MEMORY ADDRESS DECODING
(cont’)

Normally memories are divided into blocks and the output of the decoder selects a given memory block
Using simple logic gates Using the 74LS138 Using programmable logics

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

27

MEMORY ADDRESS DECODING Simple Logic Gate Address Decoder

The simplest way of decoding circuitry is the use of NAND or other gates
The fact that the output of a NAND gate is active low, and that the CS pin is also active low makes them a perfect match

A15-A12 must be 0011 in order to select the chip This result in the assignment of address 3000H to 3FFFH to this memory chip
A12 A13 A14 A15

D0 D7 D7 A0 A0 D0

A11

A11

4K*8

CS RD MEMR MEMW WR

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

28

MEMORY ADDRESS DECODING Using 74LS138 3-8 Decoder

This is one of the most widely used address decoders
The 3 inputs A, B, and C generate 8 activelow outputs Y0 – Y7
Each Y output is connected to CS of a memory chip, allowing control of 8 memory blocks by a single 74LS138

In the 74LS138, where A, B, and C select which output is activated, there are three additional inputs, G2A, G2B, and G1
G2A and G2B are both active low, and G1 is active high If any one of the inputs G1, G2A, or G2B is not connected to an address signal, they must be activated permanently either by Vcc or ground, depending on the activation level

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

Other widely used decoders are programmable logic chips such as PAL and GAL chips
One disadvantage of these chips is that one must have access to a PAL/GAL software and burner, whereas the 74LS138 needs neither of these The advantage of these chips is that they are much more versatile since they can be programmed for any combination of address ranges

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

32

INTERFACING EXTERNAL ROM

The 8031 chip is a ROMless version of the 8051
It is exactly like any member of the 8051 family as far as executing the instructions and features are concerned, but it has no on-chip ROM To make the 8031 execute 8051 code, it must be connected to external ROM memory containing the program code

8031 is ideal for many systems where the on-chip ROM of 8051 is not sufficient, since it allows the program size to be as large as 64K bytes
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University
33

INTERFACING EXTERNAL ROM EA Pin

For 8751/89C51/DS5000-based system, we connected the EA pin to Vcc to indicate that the program code is stored in the microcontroller’s on-chip ROM
To indicate that the program code is stored in external ROM, this pin must be connected to GND

Since the PC (program counter) of the 8031/51 is 16-bit, it is capable of accessing up to 64K bytes of program code
In the 8031/51, port 0 and port 2 provide the 16-bit address to access external memory
P0 provides the lower 8 bit address A0 – A7, and P2 provides the upper 8 bit address A8 – A15 P0 is also used to provide the 8-bit data bus D0 – D7

P0.0 – P0.7 are used for both the address and data paths
address/data multiplexing
Department of Computer Science and Information Engineering National Cheng Kung University

Normally ALE = 0, and P0 is used as a data bus, sending data out or bringing data in Whenever the 8031/51 wants to use P0 as an address bus, it puts the addresses A0 – A7 on the P0 pins and activates ALE = 1 Address/Data Multiplexing

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

PSEN (program store enable) signal is an output signal for the 8031/51 microcontroller and must be connected to the OE pin of a ROM containing the program code It is important to emphasize the role of EA and PSEN when connecting the 8031/51 to external ROM
When the EA pin is connected to GND, the 8031/51 fetches opcode from external ROM by using PSEN

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

38

INTERFACING EXTERNAL ROM PSEN
(cont’)

The connection of the PSEN pin to the OE pin of ROM
In systems based on the 8751/89C51/ DS5000 where EA is connected to Vcc, these chips do not activate the PSEN pin
This indicates that the on-chip ROM contains program code

Department of Computer Science and Information Engineering National Cheng Kung University

39

INTERFACING EXTERNAL ROM On-Chip and Off-Chip Code ROM

In an 8751 system we could use onchip ROM for boot code and an external ROM will contain the user’s program
We still have EA = Vcc,
Upon reset 8051 executes the on-chip program first, then When it reaches the end of the on-chip ROM, it switches to external ROM for rest of program
On-chip and Off-chip Program Code Access
8031/51 EA = GND 8051 EA = Vcc 8052 EA = Vcc On-chip

0000 Off Chip

0000 On-chip 0FFF 1000 Off Chip

0000 1FFF 2000

Off Chip

FFFF

~

~

~ FFFF

~

~
FFFF

~

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

40

INTERFACING EXTERNAL ROM On-Chip and Off-Chip Code ROM
(cont’)

Discuss the program ROM space allocation for each of the following cases. (a) EA = 0 for the 8751 (89C51) chip. (b) EA = Vcc with both on-chip and off-chip ROM for the 8751. (c) EA = Vcc with both on-chip and off-chip ROM for the 8752. Solution: (a) When EA = 0, the EA pin is strapped to GND, and all program fetches are directed to external memory regardless of whether or not the 8751 has some on-chip ROM for program code. This external ROM can be as high as 64K bytes with address space of 0000 – FFFFH. In this case an 8751(89C51) is the same as the 8031 system. (b) With the 8751 (89C51) system where EA=Vcc, it fetches the program code of address 0000 – 0FFFH from on-chip ROM since it has 4K bytes of on-chip program ROM and any fetches from addresses 1000H – FFFFH are directed to external ROM. (c) With the 8752 (89C52) system where EA=Vcc, it fetches the program code of addresses 0000 – 1FFFH from on-chip ROM since it has 8K bytes of on-chip program ROM and any fetches from addresses 2000H – FFFFH are directed to external ROM
Department of Computer Science and Information Engineering National Cheng Kung University

HANEL

41

8051 DATA MEMORY SPACE Data Memory Space

The 8051 has 128K bytes of address space
64K bytes are set aside for program code
Program space is accessed using the program counter (PC) to locate and fetch instructions In some example we placed data in the code space and used the instruction MOVC A,@A+DPTR to get data, where C stands for code

The other 64K bytes are set aside for data
The data memory space is accessed using the DPTR register and an instruction called MOVX, where X stands for external – The data memory space must be implemented externally
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University

42

8051 DATA MEMORY SPACE External ROM for Data

We use RD to connect the 8031/51 to external ROM containing data
For the ROM containing the program code, PSEN is used to fetch the code

MOVX is a widely used instruction allowing access to external data memory space

To bring externally stored data into the CPU, we use the instruction MOVX A,@DPTR

An external ROM uses the 8051 data space to store the look-up table (starting at 1000H) for DAC data. Write a program to read 30 Bytes of these data and send it to P1. Although both MOVC Solution: A,@A+DPTR and MYXDATA EQU 1000H MOVX A,@DPTR look COUNT EQU 30 very similar, one is … used to get data in the MOV DPTR,#MYXDATA code space and the MOV R2,#COUNT other is used to get AGAIN: MOVX A,@DPTR data in the data space MOV P1,A of the microcontroller INC DPTR DJNZ R2,AGAIN
Department of Computer Science and Information Engineering National Cheng Kung University
44

HANEL

8051 DATA MEMORY SPACE MOVX Instruction
(cont’)

Show the design of an 8031-based system with 8K bytes of program ROM and 8K bytes of data ROM. Solution: Figure 14-14 shows the design. Notice the role of PSEN and RD in each ROM. For program ROM, PSEN is used to activate both OE and CE. For data ROM, we use RD to active OE, while CE is activated by a Simple decoder.

8031 Connection to External Data ROM and External Program ROM

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

45

8051 DATA MEMORY SPACE External Data RAM

To connect the 8051 to an external SRAM, we must use both RD (P3.7) and WR (P3.6)

In writing data to external data RAM, we use the instruction MOVX @DPTR,A
(a) Write a program to read 200 bytes of data from P1 and save the data in external RAM starting at RAM location 5000H. (b) What is the address space allocated to data RAM in Figure 14-15? Solution: (a) RAMDATA COUNT

Assume that we have an 8031-based system connected to a single 64K×8 (27512) external ROM chip
The single external ROM chip is used for both program code and data storage
For example, the space 0000 – 7FFFH is allocated to program code, and address space 8000H – FFFFH is set aside for data

In accessing the data, we use the MOVX instruction

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

48

8051 DATA MEMORY SPACE Single External ROM for Code and Data
(cont’)

To allow a single ROM chip to provide both program code space and data space, we use an AND gate to signal the OE pin of the ROM chip

A Single ROM for BOTH Program and Data
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University
49

8051 DATA MEMORY SPACE 8031 System with ROM and RAM

Assume that we need an 8031 system with 16KB of program space, 16KB of data ROM starting at 0000, and 16K of NV-RAM starting at 8000H. Show the design using a 74LS138 for the address decoder. Solution: The solution is diagrammed in Figure 14-17. Notice that there is no need for a decoder for program ROM, but we need a 74LS138 decoder For data ROM and RAM. Also notice that G1 = Vcc, G2A = GND, G2B = GND, and the C input of the 74LS138 is also grounded since we Use Y0 – Y3 only. 8031 Connection to External Program ROM,

Data RAM, and Data ROM

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

50

8051 DATA MEMORY SPACE Interfacing to Large External Memory

In some applications we need a large amount of memory to store data
The 8051 can support only 64K bytes of external data memory since DPTR is 16-bit

To solve this problem, we connect A0 – A15 of the 8051 directly to the external memory’s A0 – A15 pins, and use some of the P1 pins to access the 64K bytes blocks inside the single 256K×8 memory chip

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

Department of Computer Science and Information Engineering National Cheng Kung University

54

INTERFACING LCD TO 8051

LCD is finding widespread use replacing LEDs
The declining prices of LCD The ability to display numbers, characters, and graphics Incorporation of a refreshing controller into the LCD, thereby relieving the CPU of the task of refreshing the LCD Ease of programming for characters and graphics

REAL-WORLD INTERFACING I LCD, ADC, AND SENSORS

LCD Operation

Chung-Ping Young 楊中平
Home Automation, Networking, and Entertainment Lab

Dept. of Computer Science and Information Engineering National Cheng Kung University

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

Command to LCD Instruction Register Clear display screen Return home Decrement cursor (shift cursor to left) Increment cursor (shift cursor to right) Shift display right Shift display left Display off, cursor off Display off, cursor on Display on, cursor off Display on, cursor blinking Display on, cursor blinking Shift cursor position to left Shift cursor position to right Shift the entire display to the left Shift the entire display to the right Force cursor to beginning to 1st line Force cursor to beginning to 2nd line 2 lines and 5x7 matrix

LCD is busy and no information HANEL
Department of Computer Science and Information Engineering National Cheng Kung University
7

HANEL

Department of Computer Science and Information Engineering should be issued to it. National Cheng Kung University

8

2

INTERFACING LCD TO 8051 LCD Data Sheet

One can put data at any location in the LCD and the following shows address locations and how they are accessed
RS 0 R/W 0 DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 1 A A A A A A A

LCD Timing

INTERFACING LCD TO 8051 LCD Data Sheet
(cont’)

tDSW = Data set up time = 195 ns (minimum) Data
tH

tH = Data hold time = 10 ns (minimum)

E R/W RS
tAS tPWH

tDSW tAH

AAAAAAA=000_0000 to 010_0111 for line1 AAAAAAA=100_0000 to 110_0111 for line2
The upper address range can go as high as 0100111 for the 40character-wide LCD, which corresponds to locations 0 to 39 HANEL LCD Addressing for the LCDs of 40×2 size
DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0

tAH = Hold time after E has come down for both RS and R/W = 10 ns (minimum) tPWH = Enable pulse width = 450 ns (minimum) tAS = Set up time prior to E (going high) for both RS and R/W = 140 ns (minimum)

Line1 (min) 1 Line1 (max) 1 Line2 (min) 1 Line2 (max) 1

0 0 1 1

0 1 0 1

0 0 0 0

0 0 0 0

0 1 0 1

0 1 0 1

0 1 0 1

Department of Computer Science and Information Engineering National Cheng Kung University

9

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

10

INTERFACING TO ADC AND SENSORS ADC Devices

ADCs (analog-to-digital converters) are among the most widely used devices for data acquisition
A physical quantity, like temperature, pressure, humidity, and velocity, etc., is converted to electrical (voltage, current) signals using a device called a transducer, or sensor

INTERFACING TO ADC AND SENSORS ADC804 Chip

ADC804 IC is an analog-to-digital converter
It works with +5 volts and has a resolution of 8 bits Conversion time is another major factor in judging an ADC
Conversion time is defined as the time it takes the ADC to convert the analog input to a digital (binary) number In ADC804 conversion time varies depending on the clocking signals applied to CLK R and CLK IN pins, but it cannot be faster than 110 µs

We need an analog-to-digital converter to translate the analog signals to digital numbers, so microcontroller can read them

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

11

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

12

3

INTERFACING TO ADC AND SENSORS ADC804 Chip
(cont’)

Differential analog inputs where Vin = Vin (+) – Vin (-) Vin (-) is connected to ground and Vin (+) is used as the analog input to be converted

CLK IN and CLK R
CLK IN is an input pin connected to an external clock source To use the internal clock generator (also called self-clocking), CLK IN and CLK R pins are connected to a capacitor and a resistor, and the clock frequency is determined by
f =
Typical values are R = 10K ohms and C = 150 pF We get f = 606 kHz and the conversion time is 110 µs

To LEDs

10k 150 pF 4 CLK in 1 CS 2 RD 10 D GND

CS is an active low input used to activate ADC804 “output enable” a high-to-low RD pulse is used to get the 8-bit converted data out of ADC804

3 WR INTR 5

normally open START

6 7 8 9 19

Vin(+) Vin(-) A GND Vref /2

“end of conversion” When the conversion is finished, it goes low to signal the CPU that the converted data is ready to be picked up

“start conversion” When WR makes a low-tohigh transition, ADC804 starts converting the analog input value of Vin to an 8bit digital number

CLK R CLK in
CS RD D GND

D0 D1 D2 D3 D4 D5 D6 D7

18 17 16 15 14 13 12 11

1 1.1 RC

4 1 2 10

3 WR INTR 5

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

13

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

Vref/2
It is used for the reference voltage
If this pin is open (not connected), the analog input voltage is in the range of 0 to 5 volts (the same as the Vcc pin) If the analog input range needs to be 0 to 4 volts, Vref/2 is connected to 2 volts
Vref/2 Relation to Vin Range
Vref/2(v) Not connected* 2.0 1.5 1.28 1.0 0.5 Vin(V) 0 to 5 0 to 4 0 to 3 0 to 2.56 0 to 2 0 to 1 Step Size ( mV) 5/256=19.53 4/255=15.62 3/256=11.71 2.56/256=10 2/256=7.81 1/256=3.90

INTERFACING TO ADC AND SENSORS ADC804 Chip
(cont’)
+5V 20 VCC

D0-D7
The digital data output pins These are tri-state buffered
The converted data is accessed only when CS = 0 and RD is forced low

The frequency of crystal is too high, we use two D flip-flops to divide the frequency by 4

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

22

INTERFACING TO ADC AND SENSORS Interfacing Temperature Sensor

A thermistor responds to temperature change by changing resistance, but its response is not linear The complexity associated with writing software for such nonlinear devices has led many manufacturers to market the linear temperature sensor
Temperature (C) 0 25 50 75 100 Tf (K ohms) 29.490 10.000 3.893 1.700 0.817
From William Kleitz, digital Electronics

INTERFACING TO ADC AND SENSORS LM34 and LM35 Temperature Sensors

The sensors of the LM34/LM35 series are precision integrated-circuit temperature sensors whose output voltage is linearly proportional to the Fahrenheit/Celsius temperature
The LM34/LM35 requires no external calibration since it is inherently calibrated It outputs 10 mV for each degree of Fahrenheit/Celsius temperature

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

23

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

24

6

INTERFACING TO ADC AND SENSORS Signal Conditioning and Interfacing LM35

Signal conditioning is a widely used

term in the world of data acquisition
It is the conversion of the signals (voltage, current, charge, capacitance, and resistance) produced by transducers to voltage, which is sent to the input of an Ato-D converter

Getting Data From the Analog World
Analog world (temperature, pressure, etc. )

Transducer

Signal conditioning can be a current-tovoltage conversion or a signal amplification
The thermistor changes resistance with temperature, while the change of resistance must be translated into voltage in order to be of any use to an ADC
Department of Computer Science and Information Engineering National Cheng Kung University

Signal conditioning

ADC

Microcontroller

HANEL

25

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

Look at the case of connecting an LM35 to an ADC804. Since the ADC804 has 8-bit resolution with a maximum of 256 steps and the LM35 (or LM34) produces 10 mV for every degree of temperature change, we can condition Vin of the ADC804 to produce a Vout of 2560 mV full-scale output. Therefore, in order to produce the fullscale Vout of 2.56 V for the ADC804, We need to set Vref/2 = 1.28. This makes Vout of the ADC804 correspond directly to the temperature as monitored by the LM35. Temperature vs. Vout of the ADC804 Temp. (C) Vin (mV)
0 1 2 3 10 30 0 10 20 30 100 300

Notice that we use the LM336-2.5 zener diode to fix the voltage across the 10K pot at 2.5 volts. The use of the LM336-2.5 should overcome any fluctuations in the power supply
28

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

27

Department of Computer Science and Information Engineering National Cheng Kung University

7

INTERFACING TO ADC AND SENSORS ADC808/809 Chip

ADC808 has 8 analog inputs
It allows us to monitor up to 8 different transducers using only a single chip The chip has 8-bit data output just like the ADC804 The 8 analog input channels are multiplexed and selected according to table below using three address pins, A, B, and C
ADC808 Analog Channel Selection
Selected Analog Channel
IN0 IN1 IN2 IN3 IN4 IN5

Department of Computer Science and Information Engineering National Cheng Kung University

30

INTERFACING TO ADC AND SENSORS Steps to Program ADC808/809

1.

2.

Select an analog channel by providing bits to A, B, and C addresses Activate the ALE pin
It needs an L-to-H pulse to latch in the address

3.

4.

5.

Activate SC (start conversion ) by an H-to-L pulse to initiate conversion Monitor EOC (end of conversion) to see whether conversion is finished Activate OE (output enable ) to read data out of the ADC chip
An H-to-L pulse to the OE pin will bring digital data out of the chip

HANEL

Department of Computer Science and Information Engineering National Cheng Kung University

31

8

LCD AND KEYBOARD INTERFACING
The 8051 Microcontroller and Embedded Systems: Using Assembly and C
Mazidi, Mazidi and McKinlay

Chung-Ping Young 楊中平
Home Automation, Networking, and Entertainment Lab

LCD is finding widespread use replacing LEDs
The declining prices of LCD The ability to display numbers, characters, and graphics Incorporation of a refreshing controller into the LCD, thereby relieving the CPU of the task of refreshing the LCD Ease of programming for characters and graphics

Clear display screen Return home Decrement cursor (shift cursor to left) Increment cursor (shift cursor to right) Shift display right Shift display left Display off, cursor off Display off, cursor on Display on, cursor off Display on, cursor blinking Display on, cursor blinking Shift cursor position to left Shift cursor position to right Shift the entire display to the left Shift the entire display to the right Force cursor to beginning to 1st line Force cursor to beginning to 2nd line 2 lines and 5x7 matrix

;send command to LCD ;copy reg A to P1 ;RS=0 for command ;R/W=0 for write ;E=1 for high pulse ;give LCD some time ;E=0 for H-to-L pulse ;write data to LCD ;copy reg A to port 1 ;RS=1 for data ;R/W=0 for write ;E=1 for high pulse ;give LCD some time ;E=0 for H-to-L pulse

Keyboards are organized in a matrix of rows and columns
The CPU accesses both rows and columns through ports
Therefore, with two 8-bit ports, an 8 x 8 matrix of keys can be connected to a microprocessor

When a key is pressed, a row and a column make a contact
Otherwise, there is no connection between rows and columns

It is the function of the microcontroller to scan the keyboard continuously to detect and identify the key pressed To detect a pressed key, the microcontroller grounds all rows by providing 0 to the output latch, then it reads the columns
If the data read from columns is D3 – D0 = 1111, no key has been pressed and the process continues till key press is detected If one of the column bits has a zero, this means that a key press has occurred
For example, if D3 – D0 = 1101, this means that a key in the D1 column has been pressed After detecting a key press, microcontroller will go through the process of identifying the key

Starting with the top row, the microcontroller grounds it by providing a low to row D0 only
It reads the columns, if the data read is all 1s, no key in that row is activated and the process is moved to the next row

It grounds the next row, reads the columns, and checks for any zero
This process continues until the row is identified

After identification of the row in which the key has been pressed
Find out which column the pressed key belongs to
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

20

KEYBOARD INTERFACING Grounding Rows and Reading Columns
(cont’)

Example 12-3 From Figure 12-6, identify the row and column of the pressed key for each of the following. (a) D3 – D0 = 1110 for the row, D3 – D0 = 1011 for the column (b) D3 – D0 = 1101 for the row, D3 – D0 = 0111 for the column Solution : From Figure 13-5 the row and column can be used to identify the key. (a) The row belongs to D0 and the column belongs to D2; therefore, key number 2 was pressed. (b) The row belongs to D1 and the column belongs to D3; therefore, key number 7 was pressed.
D0 D1 D2 D3

Program 12-4 for detection and identification of key activation goes through the following stages:
1.

To make sure that the preceding key has been released, 0s are output to all rows at once, and the columns are read and checked repeatedly until all the columns are high
When all columns are found to be high, the program waits for a short amount of time before it goes to the next stage of waiting for a key to be pressed

To see if any key is pressed, the columns are scanned over and over in an infinite loop until one of them has a 0 on it
Remember that the output latches connected to rows still have their initial zeros (provided in stage 1), making them grounded After the key press detection, it waits 20 ms for the bounce and then scans the columns again (a) it ensures that the first key press detection was not an erroneous one due a spike noise (b) the key press. If after the 20-ms delay the key is still pressed, it goes back into the loop to detect a real key press

To detect which row key press belongs to, it grounds one row at a time, reading the columns each time
If it finds that all columns are high, this means that the key press cannot belong to that row – Therefore, it grounds the next row and continues until it finds the row the key press belongs to Upon finding the row that the key press belongs to, it sets up the starting address for the look-up table holding the scan codes (or ASCII) for that row

4.

To identify the key press, it rotates the column bits, one bit at a time, into the carry flag and checks to see if it is low

Upon finding the zero, it pulls out the ASCII code for that key from the look-up table otherwise, it increments the pointer to point to the next element of the look-up table
24

While ports A, B and C are used to input or output data, the control register must be programmed to select operation mode of three ports The ports of the 8255 can be programmed in any of the following modes:
1.

Mode 0, simple I/O
Any of the ports A, B, CL, and CU can be programmed as input out output All bits are out or all are in There is no signal-bit control as in P0-P3 of 8051

The more commonly used term is I/O Mode 0
Intel calls it the basic input/output mode In this mode, any ports of A, B, or C can be programmed as input or output
A given port cannot be both input and output at the same time
Example 15-1 Find the control word of the 8255 for the following configurations: (a) All the ports of A, B and C are output ports (mode 0) (b) PA = in, PB = out, PCL = out, and PCH = out Solution: From Figure 15-3 we have: (a) 1000 0000 = 80H

Notice the use of RD and WR signals This method of connecting an I/O chip to a CPU is called memory mapped I/O, since it is mapped into memory space use memory space to access I/O use instructions such as MOVX to access 8255

For Figure 15-4. (a) Find the I/O port addresses assigned to ports A, B, C, and the control register. (b) Program the 8255 for ports A, B, and C to be output ports. (c) Write a program to send 55H and AAH to all ports continuously. Solution (a)
X X X x

For Figure 15-5. (a) Find the I/O port addresses assigned to ports A, B, C, and the control register. (b) Find the control byte for PA = in, PB = out, PC = out. (c) Write a program to get data from PA and send it to both B and C. Solution: (a) Assuming all the unused bits are 0s, the base port address for 8255 is 1000H. Therefore we have: 1000H 1001H 1002H 1003H (b) PA PB PC Control register

use the DPTR register since the base address assigned to 8255 was 16-bit if it was 8-bit, we can use “MOVX A,@R0” and “MOVX @R0,A” use a logic gate to do address decoding use a 74LS138 for multiple 8255s
19

Examples 15-3 and 15-2
decode a portion of upper address A8 A15 this partial address decoding leads to what is called address aliases could have changed all x’s to various combinations of 1s and 0s
to come up with different address they would all refer to the same physical port

Make sure that all address aliases are documented, so that the users know what address are available if they want to expanded the system
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
20

For Figure 15-6. (a) Find the I/O port addresses assigned to ports A, B, C, and the control register. (b) Find the control byte for PA = out, PB = out, PC0 – PC3 = in, and PC4 – PC7 =out (c) Write a program to get data from PB and send it to PA. In addition, data from PCL is sent out to PCU. Solution: (a) The port addresses are as follows:

In 8031-based system
external program ROM is an absolute must the use of 8255 is most welcome this is due to the fact that 3031 to external program ROM, we lose the two ports P0 and P2, leaving only P1

Therefore, connecting an 8255 is the best way to gain some extra ports.
Shown in Figure 15-8

Program PC4 of the 8255 to generate a pulse of 50 ms with 50% duty cycle. Solution: To program the 8255 in BSR mode, bit D7 of the control word must be low. For PC4 to be high, we need a control word of “0xxx1001”. Likewise, for low we would need “0xxx1000” as the control word. The x’s are for “don’t care” and generally are set to zero.
MOV MOV MOVX ACALL MOV MOVX ACALL a,#00001001B R1,#CNTPORT @R1,A DELAY A,00001000B @R1,A DELAY ;control byte for PC4=1 ;load control reg port ;make PC4=1 ;time delay for high pulse ;control byte for PC4=0 ;make PC4=0
D0
WR RD A2 A7

OTHER MODES OF THE 8255
8255 in Mode 1: I/O With Handshaking Capability

One of the most powerful features of 8255 is to handle handshaking signals Handshaking refers to the process of two intelligent devices communicating back and forth
Example--printer

Mode 1: outputting data with handshaking signals
As show in Figure 15-14 A and B can be used to send data to device with handshaking signals Handshaking signals are provided by port C Figure 15-15 provides a timing diagram

OTHER MODES OF THE 8255
8255 in Mode 1: I/O With Handshaking Capability (cont’)

The following paragraphs provide the explanation of and reasoning behind handshaking signals only for port A, but in concept they re exactly the same as for port B
OBFa (output buffer full for port A)
an active-low signal going out of PC7 indicate CPU has written a byte of data in port A OBFa must be connected to STROBE of the receiving equipment (such as printer) to inform it that it can now read a byte of data from the Port A latch

OTHER MODES OF THE 8255
8255 in Mode 1: I/O With Handshaking Capability (cont’)

ACKa (acknowledge for port A)
active-low input signal received at PC6 of 8255 Through ACK, 8255 knows that the data at port A has been picked up by the receiving device When the receiving device picks up the data at port A, it must inform the 8255 through ACK 8255 in turn makes OBFa high, to indicate that the data at the port is now old data OBFa will not go low until the CPU writes a new byte pf data to port A

INTRa (interrupt request for port A)
Active-high signal coming out of PC3 The ACK signal is a signal of limited duration

OTHER MODES OF THE 8255
8255 in Mode 1: I/O With Handshaking Capability (cont’)

When it goes active it makes OBFa inactive, stays low for a small amount of time and then goes back to high it is a rising edge of ACK that activates INTRa by making it high This high signal on INTRa can be used to get the attention of the CPU The CPU is informed through INTRa that the printer has received the last byte and is ready to receive another one INTRa interrupts the CPU in whatever it is doing and forces it to write the next byte to port A to be printed It is important to note that INTRa is set to 1 only if INTEa, OBF, and ACKa are all high It is reset to zero when the CPU writes a byte to port A
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

HANEL

46

OTHER MODES OF THE 8255
8255 in Mode 1: I/O With Handshaking Capability (cont’)

INTEa (interrupt enable for port A)
The 8255 can disable INTRa to prevent it if from interrupting the CPU It is internal flip-plop designed to mask INTRa It can be set or reset through port C in BSR mode since the INTEa flip-flop is controlled through PC6 INTEb is controlled by PC2 in BSR mode

Status word
8255 enables monitoring of the status of signals INTR, OBF, and INTE for both ports A and B This is done by reading port C into accumulator and testing the bits This feature allows the implementation of polling instead of a hardware interrupt
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN

47

OTHER MODES OF THE 8255 Printer Signal

To understand handshaking with the 8255, we give an overview of printer operation, handshaking signals The following enumerates the steps of communicating with a printer

1. A byte of data is presented to the data bus of the printer 2. The printer is informed of the presence of a byte of data to be printed by activating its Strobe input signal 3. whenever the printer receives the data it informs the sender by activating an output signal called ACK (acknowledge) 4. signal ACK initiates the process of providing another byte of data to printer

As we can see from the steps above, merely presenting a byte of data to the printer is not enough
The printer must be informed of the presence of the data At the time the data is sent, the printer might be busy or out of paper
So the printer must inform the sender whenever it finally pick up the data from its data bus

Fig 15-16 and 15-17 show DB-25 and Centronics sides of the printer cable Connection of the 8031/51 with the printer and programming are left to the reader to explore
HANEL
Department of Computer Science and Information Engineering National Cheng Kung University, TAIWAN
50

Table 15-3. Centronics Printer Specification
Serial Return 19 Signal STROBE Direction IN Description STROBE pulse to read data in. Pulse width must be more than 0.5 μs at receiving terminal. The signal level is normally “high”; read-in of data is performed at the “low” level of this signal. These signals represent information of the 1st to 8th bits of parallel data, respectively. Each signal is at “high” level when data is logical “1”, and “low” when logical “0” ““ ““ ““ ““ ““ ““ ““ Approximately 0.5 μs pulse; “low” indicates data has been received and printer is ready for data. A “high” signal indicates that the printer cannot receive data. The signal becomes “high” in the following case: (1)during data entry, (2) during printing operation,(3)in “off-line” status, (4)during printer error status. A “high” signal indicates that printer is out of paper Indicates that the printer is in the state selected.

Description When the signal is at ”low” level, the paper is fed automatically one line after printing. (The signal level can be fixed to “low” with DIP SW pin 2-3 provided on the control circuit board.) Not used Logic GND level Printer chassis GND. In the printer, chassis GND and the logical GND are isolated from each other. Not used “Twisted-pair return” signal; GND level When this signal becomes “low” the printer controller is reset to its initial state and the print buffer is cleared. Normally at “high” level; its pulse width must be more than 50μs at receiving terminal The level of this signal becomes “low” when printer is in “paper end”, “off-line”, and error state Same as with pin numbers 19 t0 30 Not used Pulled up to +5V dc through 4.7 K ohms resistance. Data entry to the printer is possible only when the level of this signal is “low” .(Internal fixing can be carried out with DIP SW 1-8. The condition at the time of shipment is set “low” for this signal.)