You are on page 1of 149

MPMC UNIT 4

8051
Prof. Videet Acharya
videet.acharya@gmail.com
8051 Architecture
 The Key features of the 8051 Microcontroller
 4 KB on-chip ROM (Program memory).
 128 bytes on-chip RAM (Data memory).
 The 8-bit data bus (bidirectional).
 16-bit address bus (unidirectional).
 Two 16-bit timers.
 Instruction cycle of 1 microsecond with 12 MHz crystal.
 Four 8-bit input/output ports.
 128 user-defined flags.
 Four register banks of 8 bit each.
 16-byte bit-addressable RAM.
 The general purpose registers are 32 each is 8-bit.
 8051 has two external and three internal interrupts.
 8051 microcontroller - some special function features - UARTs, ADC, Op-amp, etc.
 It has a 16-bit program counter and data pointer.
8051 Pin Configuration
 Pins 1 to 8 − known as Port 1- internally pulled up, bi-directional I/O port
 Pin 9 − RESET pin, is used to reset the microcontroller to its initial values
 Pins 10 to 17 − known as Port 3, functions like interrupts, timer input, control signals,
serial communication signals RxD and TxD, etc
 Pins 18 & 19 − used for interfacing external crystal to get the system clock
 Pin 20 − provides the power supply to the circuit(GND)
 Pins 21 to 28 − known as Port 2 - I/O port. Higher order address bus signals also
multiplexed using this port
 Pin 29 − PSEN - Program Store Enable. used to read signal from ext. program
memory
 Pin 30 − EA - External Access input. used to enable/disable ext. memory interfacing
 Pin 31 − ALE - Address Latch Enable. used to demultiplex the address-data signal of
port
 Pins 32 to 39 − known as Port 0, - I/O port. Lower order address and data bus signals
are multiplexed using this port
 Pin 40 − provide power supply to the circuit(VCC=+5V)
Special Function Registers (SFRs)
 Special Function Registers act as a control table that monitor and
control the operation of the 8051 Microcontroller.
 If you observe in Internal RAM Structure, the Address Space from
80H to FFH is allocated to SFRs
 Out of 128 Memory Locations, only 21 locations - assigned to SFRs.
Each SFR has one Byte Address and unique name which specifies its
purpose.
 Since SFRs - part of Internal RAM Structure, you can access SFRs as if
you access Internal RAM,
 main difference is address space: first 128 Bytes (00H to 7FH) is for
regular Internal RAM and next 128 Bytes (80H to FFH) is for SFRs
 As 21 of 128 SFR memory locations are assigned, it is recommended
that remaining registers or memory locations are not accessed.
List of 8051 Microcontroller Special Function Registers
Categories of 8051 Microcontroller Special
Function Registers

 The 21 Special Function Registers of 8051 Microcontroller are


categorized in to groups
 Math or CPU Registers: A and B
 Status Register: PSW (Program Status Word)
 Pointer Registers: DPTR (Data Pointer – DPL, DPH) and SP (Stack
Pointer)
 I/O Port Latches: P0 (Port 0), P1 (Port 1), P2 (Port 2) and P3 (Port 3)
 Peripheral Control Registers: PCON, SCON, TCON, TMOD, IE and IP
 Peripheral Data Registers: TL0, TH0, TL1, TH1 and SBUF
A or Accumulator (ACC)

 most important and most used


 Arithmetic Operations like Addition, Subtraction, Multiplication etc.
 Logical Operations like AND, OR, NOT etc.
 Data Transfer Operations (between 8051 and External Memory)
B (Register B)

 used along with ACC in Multiplication and Division operations


 These two operations are performed on data that are stored only in
Registers A and B.
 Multiplication, one of the operand (multiplier or multiplicand) is stored in B
Register and also the higher byte of result
 Division, B Register holds divisor and remainder of result. also be used as a
General Purpose Register for normal operations and is often used as an
Auxiliary Register by Programmers to store temporary results.
Program Status Word (PSW)
 Flag Register
 Flags are 1-bit storage elements that store and indicate the nature of the
result that is generated by execution of certain instructions
Data Pointer (DPTR – DPL and DPH)
 Data Pointer - 16-bit Register; the combination of DPL (Data Pointer Low) and DPH
(Data Pointer High) SFRs.
 can be used as single 16-bit register (as DPTR) or two 8-bit registers
 DPTR doesn’t have physical Memory Address but the DPL (Lower Byte) and DPH (Higher
Byte) have separate addresses in SFR Memory Space.
 DPL = 82H and DPH = 83H
 used by the programmer addressing external memory
Stack Pointer (SP)

 top of the Stack, indicates next data to be accessed


 accessed using PUSH, POP, CALL and RET Instructions
 8-bit register and upon reset, initialized with 07H
 writing new data byte into stack,
 SP automatically incremented by 1, the new data is written at an address SP+1
 reading data from stack,
 data is retrieved from Address in SP and SP is decremented by 1 (SP-1)
I/O Port Registers (P0, P1, P2 and P3)
 four Ports can be used as Input and/or Output
 P0, P1, P2 and P3. Each Port has corresponding register with same names (the Port Registers are also P0, P1,
P2 and P3)
 addresses of Port Registers are as follows: P0 – 80H, P1 – 90H, P2 – A0H and P3 – B0H.

 Each bit in these SFRs corresponds to one physical Pin in the 8051 Microcontroller.
 Port Registers both Bit Addressable and Byte Addressable. Writing 1 or 0 on a Port Register Bit will
reflect as appropriate voltage (5V and 0V) on corresponding Pin.
 If Port Bit is SET (1), corresponding Port Pin - Input and similarly if a Port Bit is CLEARED (0), the
corresponding Port Pin - Output. Upon reset, all the Port Bits are SET (1)
PCON (Power Control)
 control Microcontroller’s Power Modes, located at 87H
 two bits in PCON Register, can be set to Idle Mode and Power Down Mode
 PCON register is not bit addressable
 Idle Mode, will stop Clock Signal to ALU (CPU) but given to peripherals like Timer, Serial,
Interrupts, etc. to terminate Idle Mode, use Interrupt or Hardware Reset.
 Power Down Mode, oscillator stopped and power reduced to 2V. To terminate Power
Down Mode, use Hardware Reset
 Apart from these two, PCON Register used for,
 SMOD Bit in PCON Register is used to control the Baud Rate of the Serial Port
 two general purpose Flag Bits in the PCON Register
Table describes the function of each bit in PCON Register

Bit Symbol Description Additional Info

If 1, doubles the baud rate


Serial Comm. Baud Rate Modify
7 SMOD using Timer 1. If 0, normal timer
Bit
1 baud rate.

6–4 —- —

3 GF1 General Purpose User Flag (Bit 1)

2 GF0 General Purpose User Flag (Bit 0)

To enter Power Down Mode,


1 PD Power Down Bit
set to 1

To enter Idle Down Mode, set


0 IDL Idle Mode Bit
to 1
SCON (Serial Control)

 used to control Serial Port.


 located at address of 98H.
 Using SCON, you can control Operation Modes of Serial Port, Baud Rate of
Serial Port and Send or Receive Data using Serial Port
 consists of bits, automatically SET when byte is transmitted or received
 Serial Port Mode Selection Bits (SM0 and SM1) determine mode of UART and
also baud
Function of each bit in the SCON Register

Bit Symbol Description

7 SM0 Serial Port Mode Selection Bit 0

6 SM1 Serial Port Mode Sélection Bit 1

5 SM2 Multiprocessor Comm. Bit

4 REN Receive Enable Bit

3 TB8 Transmitted Bit 8


2 RB8 Received Bit 8

1 TI Transmit Interrupt Flag

0 RI Receive Interrupt Flag


Overview of Serial Port Mode Selection Bits to configure
Serial Port (UART) of 8051

SM0 SM1 Mode Description Baud Rate

Fixed Baud Rate


0 0 0 8-Bit Synchronous Shift Register Mode
(Frequency of oscillator / 12)

8-bit Standard UART Variable Baud Rate (Can be set


0 1 1
mode by Timer 1)

Fixed Baud Rate


1 0 2 9-bit Multiprocessor Comm. mode (Frequency of oscillator / 32 or
Frequency of oscillator / 64

Variable Baud Rate (Can be set


1 1 3 9-bit Multiprocessor Comm. mode
by Timer 1)
TCON (Timer Control)

 start or stop the Timers


 Consists bits to indicate if the Timers has overflowed
 consists of Interrupt related bits
Bit Symbol Description Additional Info

Set when Timer 1 overflows (all 1s to 0).


7 TF1 Timer 1 Overflow Flag Cleared when processor executes ISR at
001BH.

To enable Timer/Counter, set to 1. Clear to


6 TR1 Timer 1 Run Control Bit
halt the timer.

Set when Timer 0 overflows (all 1s to 0).


5 TF0 Timer 0 Overflow Flag Cleared when processor executes ISR at
000BH.

To enable Timer/Counter, set to 1. Clear to


4 TR0 Timer 0 Run Control Bit
halt the timer.

Set when HIGH to LOW is received on INT1


3 IE1 Ext. Interrupt 1 Edge Flag (P3.3). Cleared when processor executes ISR
at 0013H.

If 1, Interrupt 1 occurs on falling edge. If 0,


2 IT1 Ext. Interrupt 1 Type Control Bit
Interrupt 1 occurs on low level.

Set to 1 when HIGH to LOW is received on


1 IE0 Ext. Interrupt 0 Edge Flag INT0 (P3.2). Cleared when processor
executes ISR at 0003H.

If 1, Interrupt 0 occurs on falling edge. If 0,


0 IT0 Ext. Interrupt 0 Type Control Bit
Interrupt 0 occurs on low level.
TMOD (Timer Mode)
 used to set Operating Modes of the Timers T0 and T1.
 lower four bits are used to configure Timer0
 higher four bits are used to configure Timer1

Bit Symbol Description

7/3 Gate OR Gate Enable Bit

6/2 C/Tx Select Timer or Counter Mode

5/1 TxM1 Timer / Counter Operating Mode Select Bit 1

4/0 TxM0 Timer / Counter Operating Mode Select Bit 0


TMOD (Timer Mode)
 Gatex bit used to operate Timerx with respect to INTx pin or regardless of INTx
pin.
 GATE1 = 1 ==> Timer1 operated only if TR1 (TCON) is SET and Signal on INT1 is HIGH.
 GATE1 = 0 ==> Timer1 operated irrespective of Signal on INT1 pin but TR1 (TCON)
must be SET.
 GATE0 = 1 ==> Timer0 operated only if TR0 (TCON) is SET and Signal on INT0 is HIGH.
 GATE0 = 0 ==> Timer0 operated irrespective of Signal on INT0 pin but TR0 (TCON)
must be SET.
 C/Tx bit used to select source of pulses for Timer to count.
 C/T1 = 1 ==> Timer1 counts pulses from Pin T1 (P3.5) (Counter Mode)
 C/T1 = 0 ==> Timer1 counts pulses from internal oscillator (Timer Mode)
 C/T0 = 1 ==> Timer0 counts pulses from Pin T0 (P3.4) (Counter Mode)
 C/T0 = 0 ==> Timer0 counts pulses from internal oscillator (Timer Mode)
TxM0 TxM1 Mode Description

0 0 0 13-bit Timer Mode (THx – 8-bit and TLx – 5-bit)

0 1 1 16-bit Timer Mode

1 0 2 8-bit Auto Reload Timer Mode

1 1 3 Two 8-bit Timer Mode or Split Timer Mode


IE (Interrupt Enable)
 IE or Interrupt Enable Register used to enable or disable individual interrupts.
 bit is SET, interrupt is enabled, the bit is cleared, interrupt is disabled.
 Bit7 of the IE register i.e., EA bit is used to enable or disable all interrupts.

Bit Symbol Description Additional Info

If set to 1, individual interrupts can be enabled. If set


7 EA Global Interrupt Enable Bit.
to 0, all interrupts are disabled.

6 — —
5 ET2 Reserved
If set to 1, Serial Port interrupt is enabled. If set to 0,
4 ES Serial Port Interrupt Enable Bit
Serial Port interrupt is disabled.

If set to 1, Timer 1 Overflow interrupt is enabled. If set


3 ET1 Timer 1 Overflow Interrupt Enable Bit
to 0, Timer 1 Overflow interrupt is disabled.

If set to 1, Ext. Interrupt 1 is enabled. If set to 0, Ext.


2 EX1 Ext. Interrupt 1 Enable Bit
Interrupt 1 is disabled.

If set to 1, Timer 0 Overflow interrupt is enabled. If set


1 ET0 Timer 0 Overflow Interrupt Enable Bit
to 0, Timer 0 Overflow interrupt is disabled.

If set to 1, Ext. Interrupt 0 is enabled. If set to 0, Ext.


0 EX0 Ext. Interrupt 0 Enable Bit
Interrupt 0 is disabled.
IP (Interrupt Priority)
 set priority of interrupt as High or Low.
 bit is CLEARED, interrupt low priority, bit is SET, the interrupt high priority

Bit Symbol Description

7 — —
6 — —
5 PT2 Reserved

4 PS Priority of Serial Port Interrupt

3 PT1 Priority of Timer 1 Overflow Interrupt

2 PX1 Priority of Ext. Interrupt 1

1 PT0 Priority of Timer 0 Overflow Interrupt

0 PX0 Priority of Ext. Interrupt 0


SBUF (Serial Data Buffer)

 used to hold the serial data while transmission or reception


TL0/TH0 (Timer 0 Low/High)
 Timer 0 consists of two SFRs: TL0 and TH0.
 TL0 is the lower byte
 TH0 is the higher byte
 together they form 16-bit Timer0 Register
TL1/TH1 (Timer 1 Low/High)
I/O Pins Ports and Circuits
Input/Output Ports
 4 I/O ports each - 8 bits which can be configured as inputs or
outputs.
 Accordingly, total 32 i/o pins enabling it to be connected to
peripheral devices that are available for use.
 Pin configuration, to be configured as input (1) or output (0),
depends on logic state.
 configure a pin as output, apply a logic (0) to appropriate I/O
port bit
 voltage level on appropriate pin will be 0.
 configure pin as input, apply a logic (1) to appropriate port.
 voltage level on appropriate pin will be 5V (as is the case with any TTL
input).
Input/Output (I/O) pin
 Figure below illustrates simplified schematic of all circuits within microcontroler
connected to one of its pins
 refers to all pins except those of P0 port which do not have pull-up resistors built-in
Output pin
 logic zero (0) is applied to bit of P register
 output FE transistor is turned on, thus connecting appropriate pin to ground
Input pin
 Logic 1 applied to bit of P register
 output FE transistor is turned off and appropriate pin remains connected to power supply
voltage over pull-up resistor of high resistance
Port 0
 characterized by two functions.
 If external memory is used then lower address byte (addresses A0-A7) is applied on it.
 Otherwise, all bits of this port are configured as inputs/outputs.
 other function is expressed when it is configured as an output
 Unlike other ports consisting of pins with built-in pull-up resistor connected by its end to
5 V power supply
 pins of this port have this resistor left out
 This apparently small difference has its consequences:
 Input Configuration: acts as if it “floats”. Such an input has unlimited input resistance and
indetermined potential.
 Output Configuration: acts as “open drain”. By applying logic 0 to port bit, appropriate
pin will be connected to ground (0V). By applying logic 1, external output will keep on
“floating”.
 to apply logic 1 (5V) on output pin, it is necessary to have external pull-up resistor
Port 1
 P1 is a true I/O port
 doesn't have any alternative functions as is the case with P0,
 can be configured as general I/O only

 has pull-up resistor built-in, is completely compatible with TTL circuits.

Port 2
 P2 acts similarly to P0 when external memory is used.
 Pins occupy addresses intended for external memory chip.
 This time it is about the higher address byte with addresses A8-A15.
 When no memory is added: used as a general input/output port like P1

Port 3
 can be used as general I/O
 but they also have an alternative function
 to use these alternative functions, logic (1) applied to appropriate bit of P3 register.
 In terms of hardware, similar to P0, except that its pins have pull-up resistor built-in.
Current limitations

 configured as outputs (logic (0)), single port pins can


receive a current of 10mA
 If all 8 bits of a port are active, a total current must be
limited to 15mA (port P0: 26mA).
 If all ports (32 bits) are active, total maximum current
must be limited to 71mA.
 pins are configured as inputs (logic 1), built-in pull-up
resistors provide very weak current, but strong enough to
activate up to 4 TTL inputs of LS series
Addressing Modes
8051 Addressing Modes

Immediate Addressing
Register Addressing
Direct Addressing
Register – Indirect Addressing
Indexed Addressing
Immediate Addressing
 operand, which follows Opcode, is constant data of either 8 or 16 bits.
 The name Immediate Addressing came from the fact that constant data to
be stored in memory immediately follows Opcode.
 constant value to be stored is specified in instruction itself rather than taking
from register.
 destination register to which the constant data must be copied should be the
same size as operand mentioned in instruction.
 Example: MOV A, #030H
 Accumulator is loaded with 30 (hexadecimal)
 # in operand indicates that it is data and not address of Register.
 Immediate Addressing is very fast as data given in instruction itself.
Register Addressing

 one of eight registers (R0 – R7) is specified as Operand in


Instruction.
 important to select appropriate Bank with help of PSW Register.
 Example: MOV A, R5
 8-bit content of Register R5 of Bank0 is moved to Accumulator.
Direct Addressing

address of data is specified as Operand in


instruction.
can access any register or on-chip variable
includes general purpose RAM, SFRs, I/O Ports,
Control registers.
Example: MOV A, 47H
data in the RAM location 47H is moved to
Accumulator.
Register Indirect Addressing
 Indirect Addressing Mode or Register Indirect Addressing
Mode
 address of Operand is specified as content of Register.
 Example: MOV A, @R1
 @ symbol indicates that the addressing mode is indirect.
 If contents of R1 is 56H, for example, then operand is in internal
RAM location 56H. If contents of RAM location 56H is 24H, then
24H is moved into accumulator.
 Only R0 and R1 are allowed in Indirect Addressing Mode.
 These register in indirect addressing mode are called as
Pointer registers.
Indexed Addressing Mode
 effective address of Operand is the sum of base register
and offset register
 Base Register can be either Data Pointer (DPTR) or
Program Counter (PC) while Offset register is
Accumulator (A).
 MOVC and JMP instructions can be used
 useful when retrieving data from look-up tables.
 Example: MOVC A, @A+DPTR
 address for operand is sum of contents of DPTR and
Accumulator.
Instruction set
PROGRAM
DATA TRANSFER ARITHMETIC LOGICAL BOOLEAN
BRANCHING

MOV ADD ANL CLR LJMP


MOVC ADDC ORL SETB AJMP
MOVX SUBB XRL MOV SJMP
PUSH INC CLR JC JZ
POP DEC CPL JNC JNZ
XCH MUL RL JB CJNE
XCHD DIV RLC JNB DJNZ
DA A RR JBC NOP
RRC ANL LCALL
SWAP ORL ACALL
CPL RET
RETI
JMP
Format of Instructions
 Instruction consists of Opcode (short of Operation – Code) followed by Operand(s) of
size Zero Byte, One Byte or Two Bytes.
 Op-Code part of instruction contains Mnemonic, which specifies type of operation to
be performed.
 Mnemonics or Opcode part of instruction are of One Byte size.
 Operand part of instruction, defines data being processed by instructions, one of
following:
 No Operand, Data value, I/O Port, Memory Location, CPU register
 There can multiple operands and format of instruction is as follows:
 MNEMONIC DESTINATION OPERAND, SOURCE OPERAND
 simple instruction consists of just the opcode.
 Others may include one or more operands
 Instruction can be one-byte instruction, which contains only opcode, or two-byte
instructions, where second byte is operand or three byte instructions, where operand
makes up second and third byte.
Types of Instructions
 Data Transfer Instructions
 Arithmetic Instructions
 Logical Instructions
 Boolean or Bit Manipulation Instructions
 Program Branching Instructions
Data Transfer Instructions
Mnemonic Description

MOV Move Data

MOVC Move Code

MOVX Move External Data

PUSH Move Data to Stack

POP Copy Data from Stack

XCH Exchange Data between two Registers

XCHD Exchange Lower Order Data between two Registers


Arithmetic Instructions
Mnemonic Description

ADD Addition without Carry

ADDC Addition with Carry

SUBB Subtract with Carry

INC Increment by 1

DEC Decrement by 1

MUL Multiply

DIV Divide

DAA Decimal Adjust the Accumulator (A Register)


Logical Instructions
Mnemonic Description

ANL Logical AND


ORL Logical OR
XRL Ex-OR
CLR Clear Register
CPL Complement the Register
RL Rotate a Byte to Left

RLC Rotate a Byte and Carry Bit to Left

RR Rotate a Byte to Right

RRC Rotate a Byte and Carry Bit to Right

SWAP Exchange lower and higher nibbles in a Byte


Boolean or Bit Manipulation Instructions
Mnemonic Description

CLR Clear a Bit (Reset to 0)


SETB Set a Bit (Set to 1)
MOV Move a Bit
JC Jump if Carry Flag is Set
JNC Jump if Carry Flag is Not Set
JB Jump if specified Bit is Set

JNB Jump if specified Bit is Not Set

JBC Jump if specified Bit is Set and also clear the Bit

ANL Bitwise AND


ORL Bitwise OR
CPL Complement the Bit
Program Branching Instructions
Mnemonic Description
LJMP Long Jump (Unconditional)
AJMP Absolute Jump (Unconditional)
SJMP Short Jump (Unconditional)
JZ Jump if A is equal to 0
JNZ Jump if A is not equal to 0
CJNE Compare and Jump if Not Equal

DJNZ Decrement and Jump if Not Zero


NOP No Operation
LCALL Long Call to Subroutine
ACALL Absolute Call to Subroutine (Unconditional)
RET Return from Subroutine
RETI Return from Interrupt
JMP Jump to an Address (Unconditional)
Assembly Language Directives
 ORG – Set Origin
 start assembling from Program Memory Address 0000H
 also the address from which Microcontroller will start executing code
 Example:
 ORG 0000H ; Tells the Assembler to assemble the next statement at 0000H
 LJMP MAIN ; Code Memory at 0000H. Jump to MAIN.
 ORG 000BH ; Tells the Assembler to assemble the next statement at 000BH
 MAIN: NOP ; Code Memory at 000BH. MAIN starts here.
 END
 used to stop assembling process
 last statement in program, cannot have a Label
 statements beyond END will not be processed
 Example
 ORG 0000H
 MOV A, 20H
 MOV R0, #30
 END
DB AND EQU
 ORG 0000H
 DB 10 ; Define Byte 10 (Decimal) and store at 0000H
 DB 30H ; Define Byte 30 (HEX) and store at 0001H
 DB ‘STRING’ ; Define String ‘STRING’ and store at 0002H to 0007H
 DB 00001111B ; Define Byte 00001111 (Binary) and store at 0008H
 DB 1234H ; Define Byte 34 (HEX) and store at 0009H. Only lower
byte is accepted as DB can allocate only a Byte of Memory

 TMP EQU #30 ; Assigns the value #30 to the name TMP
 RED_LED EQU P1.0 ; P1.0 is defined as RED_LED
Toggle the LEDs ON and OFF connected to PORT1

ORG 00H ; Assembly Starts from 0000H.


; Main Program
START: MOV P1, #0XFF ; Move 11111111 to PORT1.
CALL WAIT ; Call WAIT
MOV A, P1 ; Move P1 value to ACC
CPL A ; Complement ACC
MOV P1, A ; Move ACC value to P1
CALL WAIT ; Call WAIT
SJMP START ; Jump to START
WAIT: MOV R2, #10 ; Load Register R2 with 10 (0x0A)
WAIT1: MOV R3, #200 ; Load Register R3 with 10 (0xC8)
WAIT2: MOV R4, #200 ; Load Register R4 with 10 (0xC8)
DJNZ R4, $ ; Decrement R4 till it is 0. Stay there if not 0
DJNZ R3, WAIT2 ; Decrement R3 till it is 0. Jump to WAIT2 if not 0
DJNZ R2, WAIT1 ; Decrement R2 till it is 0. Jump to WAIT1 if not 0
RET ; Return to Main Program
END ; End Assembly
Programming 8051 Timers
BASIC REGISTERS OF THE TIMER
 TIMER REGISTERS
 16 bit register, can be accessed as 8 bit registers Timer High(THx) and Timer Low (TLx)

 TMOD (Timer Mode) Register


 8-bit register used to control mode of operation of both timers.
 The high four bits (bits 4 through 7) relate to Timer 1
 the low four bits (bits 0 through 3) for timer 0.
 the lower two bits used to set timer mode and upper two bits to specify operation
Circuit to control running of timers
Bit Details High Value(1) Low Value(0)

C/T Configure for the Counter operations Configure for the Timer operations

Gate (G) Timer0 or Timer1 will be in RunMode Timer0 or Timer1 will be in RunMode
when TRX bit of TCON register is high. when TRX bit of TCON register is high
and INT0 or INT1 is high.

Bit Details 00 01 10 11

M1 M0 This is for Mode 0. This is Mode 1. This is Mode 2 This is Mode 3


(8-bit (16-bit (8-bit auto (The function
timer/counter, timer/counter) reload- depends on
with 5-bit pre- timer/counter) Timer0 or Timer1)
scaler)
Mode 1 programming
 16-bit timer; allows values of 0000 to FFFFH to be loaded into registers TL,TH
 After TH and TL are loaded with 16-bit value, the timer must be started
 “SETB TRO” for Timer 0 and “SETB TR1″ for Timer 1
 starts to count up, counts up until it reaches its limit of FFFFH
 it rolls over from FFFFH to 0000, it sets high flag bit called TF (timer flag)
 timer flag can be monitored
 When timer flag is raised,
 one option – stop timer with instructions “CLR TRO” or “CLR TR1″
 note - each timer - own timer flag: TFO for Timer 0, and TF1 for Timer 1
 After timer reaches its limit and rolls over, to repeat process TH and TL must
be reloaded with original value, and TF must be reset to 0
Mode 1 programming
 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 values

 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.

 Stop the timer.

 Clear the TF flag for the next round.

 Go back to Step 2 to load TH and TL again.


Mode 0 programming

 Mode 0 is exactly like mode 1 except that it is a 13-bit


timer instead of 16-bit
 The 13-bit counter can hold values between 0000 to
1FFFH in TH – TL
 when the timer reaches its maximum of 1FFH, it rolls over
to 0000, and TF is raised
Mode 2 programming
 8-bit timer; allows only values of 00 to FFH to be loaded TH.
 After TH is loaded with the 8-bit value, the 8051 gives copy of it to TL
 Then the timer must be started: done by “SETB TRO” and “SETB TR11‘
 After timer is started, count up by incrementing the TL counts up until it reaches its
limit of FFH.
 When it rolls over from FFH to 00, it sets high the TF (timer flag)
 TL is reloaded automatically with the original value kept by the TH register.
 To repeat process, clear TF and let it go without need by the programmer to
reload original value; makes mode 2 an auto-reload
 mode 2 is an 8-bit timer. However, it has auto-reloading capability.
 TH is loaded with initial count and copy is given to TL; leaves TH unchanged
Mode 2 programming

 Load the TMOD value register indicating which timer


(Timer 0 or Timer 1) is to be used, and select the timer
mode (mode 2).
 Load the TH registers with the initial count value.
 Start the 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.
 Clear the TF flag.
 Go back to Step 4, since mode 2 is auto-reload
Mode 3 programming

 also known as a split timer mode


 Timer 0 and 1 may be programmed to be in mode 0, 1 and 2
independently of similar mode for other timer.
 This is not true for mode 3;
 timers do not operate independently if mode 3 is chosen for
timer 0.
 Placing timer 1 in mode 3 causes it to stop counting;
 the control bit TR1 and the timer 1 flag TF1 are then used by
timer 0
Serial Port Programming
Baud rate in the 8051
 transfers and receives data serially at many different baud rates
 Relationship between crystal frequency and baud rate
 divides the crystal frequency by 12 to get the machine cycle frequency
 XTAL = 11.0592 MHz
 machine cycle frequency is 921.6 kHz
 divides machine cycle frequency of 921.6 kHz by 32 once more
 used by Timer 1 to set baud rate. 921.6 kHz divided by 32 gives 28,800 Hz
 Baud rate supported by Pentium / IBM 486 PC are
 110
 150
 300
 600
 1200
 2400
 4800
 9600
 19200
Calculation of baud rate
 Clock frequency of timer clock: f = (11.0592 MHz / 12)/32 = 28,800Hz
 Time period of each clock tick: T0 = 1/f = 1/28800
 Duration of timer : n*T0 (n is the number of clock ticks)
 9600 baud ->duration of 1 symbol: 1/9600
 1/9600 = n*T0 = n*1/28800
 n = f/9600 = 28800/9600 = 3 ->TH1 =-3
 Similarly, for baud 2400
 n = f/2400 = 12 ->TH1 = -12
 Example: set baud rate at 9600
 MOV TMOD, #20H ; timer 1,mode 2(auto reload)
 MOV TH1, #-3 ; To set 9600 baud rate
 SETB TR1 ; start timer 1
Baud rate selection
 Baud rate is selected by timer1 and when Timer 1 is used to set the baud rate
it must be programmed in mode 2 that is 8-bit, auto-reload. To get baud rates
compatible with the PC, we must load TH1 with the values shown in Table
Registers for serial communication

SBUF (serial buffer) register


8 bit register used solely for serial communication
byte of data to be transferred via TxD line must be placed in
SBUF register
SBUF holds byte of data when it is received by RxD line
can be accessed like any other register when byte is written, is
framed with start and stop bits and transferred serially via TxD
pin
when the bits are received serially via RxD, it is deframed by
eliminating stop and start bits, making byte out of data
received, and then placing it in SBUF
Registers for serial communication
 SCON (serial control) register
 SM0, SM1 - serial port mode bits
 used to specify framing format, how to calculate baud.
 if (SM0, SM1) = (0,1), mode 1: 8-bit data, 1 start bit, 1 stop bit, variable baud rate can be set
by timer.
 other three modes are rarely used and they are (SM0,SM1) = (0,0),
 mode 0: fixed baud = XTAL/12,(SM0, SM1) = (1,0),
 mode 2: 9-bit data, fixed baud,(SM0, SM1) = (1, 1),
 mode 3: 9-bit data, variable baud.
 third bit is used to select the type of processor used for communication.
 SM2 is 0 single processor communication
 SM2 is 1, multiprocessor communication.
 REN Receive Enable used to enable/disable reception
 If REN=1 accept incoming data from serial port.
 If REN=0, receiver is disabled.
 E.g. SETB REN,CLR REN, SETB SCON.4, CLR SCON.4
SCON cont.…
 TB8 which is used by modes 2 and 3 for the 8-bit transmission
 mode 1 is used the pin TB8 should be cleared
 RB8 is used by modes 2 and 3 for reception of bit 8.
 used by mode1 to store stop bit
 TI - Transmit Interrupt
 finishes transfer of 8-bit character
 sets TI to ''1'' to indicate that it is ready to transfer next character
 TI is raised at beginning of stop bit
 RI - receive interrupt
 receives a character
 removes start bit and stop bit
 puts the 8-bit character in SBUF.
 RI is set to 1 to indicate that new byte is ready to be picked up in SBUF
 RI is raised halfway through stop bit
Steps to send data serially
 Set baud rate by loading TMOD register with the value 20H, this
indicating timer 1 in mode 2 (8-bit auto-reload) to set baud rate
 The TH1 is loaded with proper values to set baud rate for serial data
transfer
 The SCON register is loaded with the value 50H, indicating serial
mode 1, where an 8- bit
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
Program to transfer letter “D” serially at
9800baud, continuously

MOV TMOD,#20H ; timer 1,mode 2(auto reload)


MOV TH1, #-3 ; 9600 baud rate
MOV SCON, #50H ; 8-bit, 1 stop, REN enabled
SETB TR1 ; start timer 1
AGAIN: MOV SBUF, #”D” ; letter “D” to transfer
HERE: JNB TI, HERE ; wait for the last bit
CLR TI ;clear TI for next char
SJMP AGAIN ; keep sending A
Importance of the TI flag

Check TI flag bit, we know whether or not 8051 is ready


to transfer another byte
TI flag bit is raised by the 8051 after transfer of data
TI flag is cleared by the programmer by instruction like
“CLR TI”
When writing a byte into SBUF, before the TI flag bit is
raised, it may lead to loss of a portion of the byte
being transferred.
Steps to receive data serially
 Set baud rate by loading TMOD register with the value 20H, this
indicating timer 1 in mode 2 (8-bit auto-reload) to set baud rate
 The TH1 is loaded with proper values to set baud rate
 The SCON register is loaded with the value 50H, indicating serial
mode 1, where an 8- bit 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 next character, go to step 5
Program to receive bytes of data serially, put them
in P2, set baud rate-9600, 8-bit data, and 1 stop bit

MOV TMOD, #20H ; timer 1,mode 2(auto reload)


MOV TH1, #-3 ; 9600 baud rate
MOV SCON, #50H ; 8-bit, 1 stop, REN enabled
SETB TR1 ; start timer 1
HERE: JNB RI, HERE ; wait for char to come in
MOV A, SBUF ; saving incoming byte in A
MOV P2, A ; send to port 1
CLR RI ; get ready to receive next byte
SJMP HERE ; keep getting data
Importance of the RI flag bit
It receives the start bit, next bit is the first bit of the
character about to be received
When the last bit is received, a byte is formed and
placed in SBUF
when stop bit is received, it makes RI = 1 indicating
entire character byte has been received and can be
read before overwritten by next data
When RI=1, received byte is in the SBUF register, copy
SBUF contents to a safe place
After the SBUF contents are copied the RI flag bit
must be cleared to 0
Increasing the baud rate

Increasing frequency of crystal


Change bit in PCON register
ORG 0 SJMP B_1 ;stay in loop indefinitely
MOV P2, #0FFH ; make P2 an input port ; ---------serial data transfer. ACC has the data-----------
MOV TMOD,#20H ;timer 1, mode 2 SEND: MOV SBUF,A ;load the data
MOV TH1, #0FAH ;4800 baud rate H_2: JNB TI,H_2 ;stay here until last bit gone
MOV SCON, #50H ; 8-bit, 1 stop, REN enabled CLR TI ; get ready for next char
SETB TR1 ; start timer 1 RET ;return to caller
MOV DPTR, #MYDATA ; load pointer for message ; ----------Receive data serially in ACC----------------
H_1: CLR A RECV: JNB RI, RECV ; wait here for char
MOV A,@A+DPTR ;get the character MOV A, SBUF ; save it in ACC
JZ B_1 ;if last character get out CLR RI ; get ready for next char
ACALL SEND ;otherwise call transfer RET ; return to caller
INC DPTR ;next one ; ------------The message---------------
SJMP H_1 ;stay in loop MYDATA: DB “We Are Ready”, 0
B_1: MOV a,P2 ;read data on P2 END
ACALL SEND ;transfer it serially
ACALL RECV ;get the serial data
MOV P1,A ;display it on LEDs
INTERRUPT PROGRAMMING IN 8051
 Microcontroller can serve several devices
 After receiving interrupt, microcontroller interrupts whatever it is doing and serves device
 program associated - interrupt service routine (ISR)
 interrupt is invoked, runs the interrupt service routine
 For every interrupt, there is fixed location set aside to hold addresses of ISRs
 Timer 0 Overflow
 Timer 1 Overflow
 Reception/Transmission of Serial Character
 External Event 0.
 External Event 1
ENABLING AND DISABLING AN INTERRUPT
 upon reset all interrupts disabled
 will be responded to by microcontroller if activated
 enabled by software
 respond to them using IE that is responsible for enabling and disabling interrupts
PROGRAMMING EXTERNAL HARDWARE
INTERRUPTS
two external hardware interrupts PIN 12 (P3.2) and Pin 13
(P3.3) - INT0 and INT1
Upon activation, 8051 finishes execution of current
instruction whatever it is executing and jumps to vector
table to perform interrupt service routine
TYPES OF INTERRUPT:
Level-Triggered Interrupt
Edge -Triggered Interrupt
LEVEL-TRIGGERED INTERRUPT
 INT0 and INT1 are normally high
 if low level signal is applied to them, it triggers Interrupt
 microcontroller stops and jumps to interrupt vector table to service interrupt
 low-level signal at INT pin must be removed before execution of last instruction of ISR, RETI
 Otherwise, another interrupt will be generated.
 called level-triggered or level-activated interrupt and is default mode upon reset
EDGE -TRIGGERED INTERRUPT
 Upon reset 8051 makes INT0 and INT1 low l Level-Triggered Interrupt
 To make them Edge -Triggered Interrupt, we must program bits of TCON Register
 TCON register holds among other bits and IT0 and IT1 flags bit determine level- or edge
triggered mode
 IT0 and IT1 are bits D0 (TCON.0) and D2(TCON.2) of TCON Register respectively
SERIAL COMMUNICATION INTERRUPT
 TI (transfer interrupt)
 raised when stop bit is transferred indicating that SBUF register is ready to
transfer next byte
 RI (received interrupt)
 raised when stop bit is received indicating that received byte needs to be
picked up before it is lost (overrun) by new incoming serial data
 only one interrupt set aside for serial communication; for both sending and
receiving data.
 interrupt bit in IE register (IE.4) is enabled, when RI or TI is raised gets interrupted
and jumps to memory location 0023H to execute the ISR
 ISR must examine TI and RI flags to see which one caused interrupt and
respond accordingly
Write a program in which the 8051 reads data from P1 and writes it to P2
continuously while giving a copy of it to the serial COM port to be transferred serially.
Assume that XTAL=11.0592. Set the baud rate at 9600.
ORG 0000H
LJMP MAIN
ORG 23H
LJMP SERIAL ;jump to serial int ISR
ORG 30H
MAIN: MOV P1,#0FFH ;make P1 an input port
MOV TMOD,#20H ;timer 1, auto reload
MOV TH1,#0FDH ;9600 baud rate
MOV SCON,#50H ;8-bit,1 stop, ren enabled
MOV IE,10010000B ;enable serial int.
SETB TR1 ;start timer 1
BACK: MOV A,P1 ;read data from port 1
MOV SBUF,A ;give a copy to SBUF
MOV P2,A ;send it to P2
SJMP BACK ;stay in loop indefinitely
;-----------------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
TIMER INTERRUPTS
 timer flag (TF) is raised when timer rolls over
 In polling TF, we have to wait until the TF is raised
 microcontroller is tied down while waiting for TF to be raised, and can’t do anything else
 If timer interrupt in IE register is enabled, whenever timer rolls over, TF is raised
 This avoids tying down controller
 interrupted in whatever it is doing, and jumps to interrupt vector table to service ISR
 can do other task until it is notified that timer has rolled over
Write a program that continuously get 8-bit data from P0 and sends it to P1 while
simultaneously creating a square wave of 200 μs period on pin P2.1. Use timer 0 to
create the square wave. Assume that XTAL = 11.0592 MHz.
;--upon wake-up go to main, avoid using memory allocated to Interrupt Vector Table
ORG 0000H
LJMP MAIN ;by-pass interrupt vector table
;--ISR for timer 0 to generate square wave
ORG 000BH ;Timer 0 interrupt vector table
CPL P2.1 ;toggle P2.1 pin
RETI ;return from ISR
;--The main program for initialization
ORG 0030H ;after vector table space
MAIN: MOV TMOD,#02H ;Timer 0, mode 2
MOV P0,#0FFH ;make P0 an input port
MOV TH0,#-92 ;TH0=A4H for -92
MOV IE,#82H ;IE=10000010 (bin) enable
;Timer 0
SETB TR0 ;Start Timer 0
BACK: MOV A,P0 ;get data from P0
MOV P1,A ;issue it to P1
SJMP BACK ;keep doing it loop
;unless interrupted by TF0
END
INTERRUPT PRIORITY
 When 8051 is powered up, priorities are assigned according to following
LCD AND KEYBOARD
INTERFACING
LCD (LIQUID CRYSTAL DISPLAY) INTERFACE
 can display numbers, characters, and graphics
 To produce proper display, information has to be periodically refreshed
 can be done by CPU or internally by LCD device itself
 Incorporating refreshing controller into LCD, relieves CPU of this task and hence
many LCDs have built-in controllers
 also facilitate flexible programming for characters and graphics
 Vss and VDD provide +5v and ground, V0 is used for controlling LCD contrast
 If RS=0, instruction command register is selected, allowing user to send command
such as clear display, cursor at home, etc.
 if RS=1, data register is selected, allowing user to send data to be displayed on
LCD
 R/W input allows user to Read/ Write information to LCD
 enable pin is used by LCD to latch information presented to its data pins
 8-bit data pins are used to send information to LCD
LCD COMMAND CODES

LCD Connections to 8051


PROGRAM TO DISPLAY CHARACTERS ON LCD
;calls time delay before sending next data/command ACALL DATAWRT ;call display subroutine
;P1.0-P1.7 are connected to LCD data pins D0-D7 AGAIN: SJMP AGAIN ;stay here
;P2.0 is connected to RS pin of LCD
;P2.1 is connected to R/W pin of LCD COMNWRT: ;send command to LCD
;P2.2 is connected to E pin of LCD MOV P1,A ;copy reg A to port 1
MOV A,#38H ;INIT. LCD 2 LINES, 5X7 MATRIX CLR P2.0 ;RS=0 for command
ACALL COMNWRT ;call command subroutine CLR P2.1 ;R/W=0 for write
ACALL DELAY ;give LCD some time SETB P2.2 ;E=1 for high pulse
MOV A,#0EH ;display on, cursor on CLR P2.2 ;E=0 for H-to-L pulse
ACALL COMNWRT ;call command subroutine RET
ACALL DELAY ;give LCD some time
MOV A,#01 ;clear LCD DATAWRT: ;write data to LCD
ACALL COMNWRT ;call command subroutine MOV P1,A ;copy reg A to port 1
ACALL DELAY ;give LCD some time SETB P2.0 ;RS=1 for DATA
MOV A,#06H ;shift cursor right CLR P2.1 ;R/W=0 for write
ACALL COMNWRT ;call command subroutine SETB P2.2 ;E=1 for high pulse
ACALL DELAY ;give LCD some time CLR P2.2 ;E=0 for H-to-L pulse
MOV A,#84H ;cursor at line 1, pos. 4 RET
ACALL COMNWRT ;call command subroutine
ACALL DELAY ;give LCD some time DELAY: MOV R3,#50 ;50 or higher for fast CPUs
MOV A,#’N’ ;display letter N HERE 2: MOV R4,#255 ;R4 = 255
ACALL DATAWRT ;call display subroutine HERE: DJNZ R4,HERE ;stay until R4 becomes 0
ACALL DELAY ;give LCD some time DJNZ R3, HERE 2
MOV A,#’O’ ;display letter O RET
KEYBOARD INTERFACING WITH 8051
 Keys in keyboard are arranged in matrix of rows and columns; controller access both rows
and columns through ports
 Using two ports, we can connect to 8x8 or 4x4 matrix keyboard; When key is pressed, row
and column make contact, otherwise there is no contact
 rows are connected to output port(Port 1) and columns are connected to input port(Port 2)
 If no key has been pressed, reading input port will yield 1s for all columns since they are all
connected to high (Vcc)
 If all rows are grounded and key is pressed, one of columns will have 0 since key pressed provides
path to ground
 It is function of controller to scan keyboard continuously to detect and identify key pressed
KEY SCAN
 to find key pressed; grounds row by sending ‘0’ on corresponding
line of output port
 then reads data at columns using input port
 If data from columns is D3-D0=1111, then no key is pressed
 If any bit of column is ‘0’, it indicates that key is pressed in that
column
 In this example, column is identified by following values
 1110 – key pressed in column 0
 1101 – key pressed in column 1
 1011 – key pressed in column 2
 0111 – key pressed in column 3
STEPS TO FIND OUT KEY PRESSED
 Beginning with row 0, grounds it by providing low to row D0 only
 then reads columns (port2); data read is all 1s, then no key in that
row is activated
 then grounds next row, reads columns, and checks for any zero
 process continues until row with zero is identified
 After identification of row in which key has been pressed, column to
which pressed key belongs is identified as discussed above - by
looking for zero in input values read
 D3 – D0 = 1101 for the row, D3 – D0 = 1011 for the column, indicate
row 1 and column 3 are selected. This indicates that key 6 is
pressed.
 D3 – D0 = 1011 for the row, D3 – D0 = 0111 for the column, indicate
row 2 and column 3 are selected. Then key ‘B’ is pressed
PROGRAM
 1. make sure that preceding key has been released, 0s are output to all rows at once, and
columns are read and checked repeatedly until all columns are high.
 all columns are found to be high, program waits for short amount of time before it goes to next
stage of waiting for key to be pressed
 2. To see if any key is pressed, columns are scanned over and over in infinite loop until one
of them has 0 on it.
 Remember that output latch is connected to rows, still have their initial zeros (in stage 1), making
them grounded.
 After key press detection, it waits for 20-ms for bounce and then scans columns again.
 ensures that first key press detection was not erroneous one due to spike noise
 After 20-ms delay, if key is still pressed, then it goes to loop (step 3) to detect actual key pressed.

 3. To detect row key pressed belongs to, grounds one row at a time, reading columns
each time.
 If all columns are high, means key press does not belong to that row. Therefore, it grounds next
row and continues until it finds row, that key pressed belongs to.
 finding row that key pressed belongs to, sets up starting address for lookup table holding scan
codes for that row
 4. To identify key pressed, it rotates column bits, one bit at a time, into carry flag and
checks to see if it is low.
 Upon finding zero, it pulls out ASCII code for that key from look-up table.
 Otherwise, it increments pointer to point to next element of look-up table.
Flowchart for Keyboard Interfacing
PROGRAM:
;keyboard subroutine. This program sends the ASCII code for pressed key to P0.1
;P1.0-P1.3 connected to rows, P2.0-P2.3 to column
MOV P2,#0FFH ;make P2 an input port
K1: MOV P1,#0 ;ground all rows at once
MOV A,P2 ;read all col
;(ensure keys open)
ANL A,00001111B ;masked unused bits
CJNE A,#00001111B,K1 ;till all keys release
K2: ACALL DELAY ;call 20 msec delay
MOV A,P2 ;see if any key is pressed
ANL A,00001111B ;mask unused bits
CJNE A,#00001111B,OVER ;key pressed, find row
SJMP K2 ;check till key pressed
OVER: ACALL DELAY ;wait 20 msec debounce time
MOV A,P2 ;check key closure
ANL A,00001111B ;mask unused bits
CJNE A,#00001111B,OVER1 ;key pressed, find row
SJMP K2 ;if none, keep polling
OVER1: MOV P1, #11111110B ;ground row 0
MOV A,P2 ;read all columns
ANL A,#00001111B ;mask unused bits
CJNE A,#00001111B,ROW_0 ;key row 0, find col.
MOV P1,#11111101B ;ground row 1
MOV A,P2 ;read all columns
ANL A,#00001111B ;mask unused bits
CJNE A,#00001111B,ROW_1 ;key row 1, find col.
MOV P1,#11111011B ;ground row 2
MOV A,P2 ;read all columns
ANL A,#00001111B ;mask unused bits
CJNE A,#00001111B,ROW_2 ;key row 2, find col.
MOV P1,#11110111B ;ground row 3
MOV A,P2 ;read all columns
ANL A,#00001111B ;mask unused bits
CJNE A,#00001111B,ROW_3 ;key row 3, find col.
LJMP K2 ;if none, false input,
ROW_0: MOV DPTR,#KCODE0 ;set DPTR=start of row 0
SJMP FIND ;find col. Key belongs to
ROW_1: MOV DPTR,#KCODE1 ;set DPTR=start of row
SJMP FIND ;find col. Key belongs to
ROW_2: MOV DPTR,#KCODE2 ;set DPTR=start of row 2
SJMP FIND ;find col. Key belongs to
ROW_3: MOV DPTR,#KCODE3 ;set DPTR=start of row 3
FIND: RRC A ;see if any CY bit low
JNC MATCH ;if zero, get ASCII code
INC DPTR ;point to next col. addr
SJMP FIND ;keep searching
MATCH: CLR A ;set A=0 (match is found)
MOVC A,@A+DPTR ;get ASCII from table
MOV P0,A ;display pressed key
LJMP K1
; ASCII LOOK-UP TABLE FOR EACH ROW
ORG 300H
KCODE0: DB ‘0’,’1’,’2’,’3’ ;ROW 0
KCODE1: DB ‘4’,’5’,’6’,’7’ ;ROW 1
KCODE2: DB ‘8’,’9’,’A’,’B’ ;ROW 2
KCODE3: DB ‘C’,’D’,’E’,’F’ ;ROW 3
EXTERNAL MEMORY
INTERFACE
EXTERNAL ROM (PROGRAM MEMORY)
INTERFACING
 Port 0 used as multiplexed data & address lines
 lower order (A7-A0) - 8 bit address in initial T cycle & higher order (A8-A15) - data bus
 8 bit address is latched using external latch & ALE signal from 8051
 Port 2 provides higher order (A15-A8) 8 bit address
 PSEN used to activate output enable signal of external ROM/EPROM
EXTERNAL RAM (DATA MEMORY) INTERFACING
 Port 0 used as multiplexed data & address lines
 Address lines - decoded using external latch; ALE signal to provide lower order (A7-A0)
address lines
 Port 2 gives higher order address lines
 RD & WR signals selects memory read & memory write operations respectively
 RD & WR signals: generally P3.6 & P3.7 pins of port 3 used to generate memory read and
memory write signals
 Remaining pins of port 3 i.e. P3.0-P3.5 can be used for other functions
Example

 Design a μController system using 8051 to Interface the external


RAM of size 16k x 8.
 Solution: Given, Memory size: 16k Which means, we require
2n=16k: n address lines
 Here n=14: A0 to A13 address lines are required
 A14 and A15 are connected through OR gate to CS pin of external RAM
 When A14 and A15 both are low (logic ‘0’), external data memory (RAM) is
selected.
Example
 Design a μController system using 8051 to interface the external
ROM of size 4k x 8.

 Solution: Given, Memory size: 4k


 i.e. we require 2n=4k :: n address lines

 Here n=12 : A0 to A11 address lines are required


 Remaining lines A0, A0, A0, A0 & PSEN are connected though OR gate to CS
& RD of external ROM
 When A0 to A0 are low (logic ‘0’), only then external ROM is selected.
Example
 Design a μController system using 8051, 16k bytes of ROM & 32k bytes of RAM. Interface
the memory such that starting address for ROM is 0000H & RAM is 8000H

 Solution:
 Given, Memory size- ROM : 16k i.e. we require 2n=16k :: n address lines
 Here n=14 :: A0 to A13 address lines are required.
 A14,A15,PSEN O Red CS when low – ROM is selected
 Memory size- RAM :32k
 i.e. we require 2n=32k :: n address lines
 Here n=15 :: A0 to A15 address lines are required.
 A15 inverted(NOT Gate) CS when high- RAM is selected.
 For RAM selection
 PSEN is used as chip select pin ROM.
 RD is used as read control signal pin
 WR is used as write control signal pin
ADC, DAC & Sensor
Interfacing
ANALOG-TO-DIGITAL CONVERTER (ADC)
INTERFACING
 ADCs (Analog-to-Digital Converters) are among most widely used devices for data acquisition.
 physical quantity, like temperature, pressure, humidity, and velocity, etc., is converted to electrical
(voltage, current) signals using device - transducer or sensor
 need Analog-to-Digital Converter to translate analog signals to digital numbers, so microcontroller can
read and process them.
 ADC has n-bit resolution where n can be 8, 10, 12, 16 or even 24 bits.
 higher-resolution ADC provides smaller step size, where step size is smallest change that can be discerned
by ADC
In addition to resolution, conversion time is another major factor in judging ADC
 Conversion time is defined as time it takes ADC to convert the analog input to digital (binary) number
 In parallel ADC, we have 8 of more pins dedicated to bringing out binary data, but
in serial ADC we have only one pin for data out
ADC804 CHIP
 ADC804 IC is an 8-bit parallel analog-to-digital converter
 It works with +5 volts and has a resolution of 8bits
 conversion time varies depending on clocking signals applied to
CLK R and CLK IN pins, but it cannot be faster than 110μs
 CLK IN is input pin connected to external clock source when
external clock is used for timing
 However, 0804 has internal clock generator.
 To use internal clock generator (also called self-clocking), CLK IN
and CLK R pins are connected to capacitor and resistor and clock
frequency is determined by
 Vref/2: (Pin 9)
 used for reference voltage
 If pin is open (not connected), analog input voltage is in range of
0 to 5 volts (same as Vcc pin)
 If analog input range needs to be 0 to 4 volts, Vref/2 is connected
to 2 volts.
 D0-D7 are digital data output pins
 are tri-state buffered and the converted data is accessed only
when CS =0 and RD is forced low
 To calculate the output voltage, use following formula

 Where Dout = digital data output (in decimal), Vin = analog


voltage, and Step size (resolution) is smallest change, which is (2 *
Vref/2)/256 for ADC 0804
 Analog ground is connected to ground of analog Vin and digital ground is
connected to ground of Vcc pin
 reason that to have ground pin is to isolate the analog Vin signal from transient
voltages caused by digital switching of output D0 – D7; contributes to accuracy of
digital data output.
 Differential analog inputs where Vin= Vin (+) – Vin (-).
 Vin (-) connected to ground and Vin(+) is used as analog input to be converted
 ADC converts analog input to its binary equivalent and holds it in internal register.
 RD is used to get the converted data out of the ADC0804 chip
 IF “output enable” ,a high-to-low RD pulse is used to get the 8-bit converted data out
of ADC804.
 INTR is “end of conversion”
 When conversion is finished; it goes low to signal that converted data is ready to be
picked up
 WR is an active low input
 It is “start conversion” When WR makes a low-to-high transition, ADC804 starts
converting the analog input value of Vin to an 8-bit digital number
 When data conversion is complete, INTR pin is forced low by ADC0804.
STEPS TO BE FOLLOWED FOR DATA CONVERSION
 Make CS= 0 and send a L-to-H pulse to pin WR to start conversion
 Monitor the INTR pin, if high keep polling but if low, conversion is complete, go to next step
 Make CS= 0 and send a H-to-L pulse to pin RD to get the data out.
8051 Connection to ADC0804 with Self-Clocking
Write a program to monitor INTR pin and bring analog input into register A. Then call
hex-to ACSII conversion and data display subroutines. Do this continuously

;p2.6=WR (start conversion needs to L-to-H pulse)


;p2.7 When low, end-of-conversion)
;p2.5=RD (a H-to-L will read the data from ADC chip)
;p1.0 – P1.7= D0 - D7 of the ADC0804

MOV P1,#0FFH ;make P1 = input


BACK: CLR P2.6 ;WR = 0
SETB P2.6 ;WR = 1 L-to-H to start conversion
HERE: JB P2.7,HERE ;wait for end of conversion
CLR P2.5 ;conversion finished, enable RD
MOV A,P1 ;read the data
ACALL CONVERSION ;hex-to-ASCII conversion
ACALL DATA_DISPLAY ;display the data
SETB P2.5 ;make RD=1 for next round
SJMP BACK
DIGITAL-TO-ANALOG (DAC) CONVERTER
 two method of creating DAC is binary weighted and R/2R ladder
 Binary Weighted DAC
 contains one resistor or current source for each bit of DAC connected to summing point
 These precise voltages or currents sum to correct output value
 one of the fastest conversion methods but suffers from poor accuracy because of high precision
required for each individual voltage or current
 Such high-precision resistors and current-sources are expensive; this type of converter is usually limited to
8-bit resolution or less
 R-2R ladder DAC,
 binary weighted DAC that uses repeating cascaded structure of resistor values R and 2R
 improves precision - relative ease - producing equal valued matched resistors (or current sources)
 wide converters perform slowly due to increasingly large RC-constants for each added R-2R link
 first criterion for judging DAC – resolution
 a function of number of binary inputs
 common ones are 8, 10, and 12 bits. No. of data bit inputs decides resolution of DAC since no. of analog
output levels is equal to 2n, where n is number of data bit inputs
 8-input DAC such as DAC0808 provides 256 discrete voltage (or current) levels of output
 12-bit DAC provides 4096 discrete voltage levels
 There also 16-bit DACs, but they are more expensive
DAC 0808
 digital inputs are converter to current (Iout), and by connecting
resistor to Iout pin, we can convert result to voltage.
 total current provided by Iout pin is function of binary numbers at
D0-D7 inputs of DAC0808 and reference current (Iref), and is as
follows

 Usually reference current is 2mA


 we connect output pin to resistor, convert this current to voltage,
and monitor output on scope
 this can cause inaccuracy; hence opamp is used to convert output
current to voltage
 assuming that Iref = 2mA, if all inputs to DAC are high, maximum
output current is 1.99mA.
Example:
Assuming that R=5K and Iref=2mA, calculate Vout for the following binary inputs:
(a) 10011001B
(b) 11001000B

Solution:
(a) Iout = 2mA(153/256) = 1.195mA and Vout = 1.195mA * 5K =5.975V
(b) Iout = 2mA(200/256) = 1.562mA and Vout = 1.562mA * 5K =7.8125V
CONVERTING IOUT TO VOLTAGE IN DAC0808
 we connect output pin lout, to resistor, convert this current to voltage, and monitor output
on scope.
 this can cause inaccuracy since input resistance of load where it is connected will also
affect output voltage.
 lref current output is isolated by connecting it to op-amp such as 741 with Rf = 5K ohms for
feedback resistor.
 Assuming that R= 5K ohms, by changing binary i/p, o/p voltage change is shown below:
 Example
 to generate stair-step ramp, set up the circuit in Figure and connect output to
oscilloscope. Then write program to send data to DAC to generate stair-step ramp
 CLR A
 AGAIN: MOV P1,A ; SEND DATA TO DAC
 INC A ; COUNT FROM 0 TO FFH
 ACALL DELAY ; LET DAC RECOVER
 SJMP AGAIN
Example
Write an ALP to generate a triangular waveform
SENSOR INTERFACING
 The LM35 series sensors are precision integrated-circuit temperature sensors whose
output voltage is linearly proportional to the Celsius (centigrade) temperature.
 The LM35 requires no external calibration since it is internally calibrated
 It outputs 10mV for each degree of centigrade temperature.
 The sensors of the LM34 series are precision integrated-circuit temperature sensors
whose output voltage is linearly proportional to the Fahrenheit temperature.
 It outputs 10mV for each degree Fahrenheit temperature.
SIGNAL CONDITIONING AND INTERFACING
LM35 TO 8051
 Signal conditioning is widely used in world of data acquisition
 most common transducers produce output in form of voltage, current, charge,
capacitance, and resistance
 we need to convert these signals to voltage in order to send input to A-to-D converter
 This conversion (modification) is commonly called signal conditioning.
 Signal conditioning can be a current-to-voltage conversion or signal amplification
 E.g., thermistor changes resistance with temperature
 change of resistance must be translated into voltages to be of any use to ADC
 Look at case of connecting LM35 to ADC0848
 ADC0848 has 8-bit resolution with maximum of 256 (28) steps and LM35 (or LM34)
produces l0 mV for every degree of temperature change, we can condition Vin of
ADC0848 to produce Vout, of 2560 mV (2.56 V) for full-scale output
 in order to produce full-scale Vout of 2.56 V for ADC0848, we need to set Vref = 2.56.
 This makes Vout, of ADC0848 correspond directly to temperature as monitored by LM35
Temperature vs. Vout for ADC0848
The LM336-2.5 zener diode to fix the voltage across the 10K pot at 2.5V
The use of the LM336-2.5 should overcome any fluctuations in the power supply

Connection to
ADC0848
and
Temperature sensor
Program

RD BIT P2.5 ;RD CONVERSION:


WR BIT P2.6 ;WR MOV B,#10
INTR BIT P2.7 ; END OF CONVERSION DIV AB
MYDATA EQU P1 ; P1.0-P1.7 = D0-D7 OF MOV R7,B
THE ADC0848 MOV B,#10
MOV P1,#0FFH ;make P1 = input DIV AB
SETB INTR MOV R6,B
BACK: CLR WR ;WR = 0 MOV R5,A
SETB WR ;WR = 1 L-to-H to start conversion RET
HERE: JB INTR, HERE ;wait for end of DATA_DISPLAY:
conversion MOV P0,R7
CLR RD ;conversion finished, enable RD ACALL DELAY
MOV A,MYDATA ;read the data MOV P0,R6
ACALL CONVERSION ;hex-to-ASCII ACALL DELAY
conversion MOV P0,R5
ACALL DATA_DISPLAY ;display the data ACALL DELAY
SETB RD ;make RD=1 for next round RET
SJMP BACK
Stepper Motor and
Waveform generation
Stepper motor Interfacing/Control using 8085 and 8051
 stepper motor is device that translates electrical pulses into mechanical movement in
steps of fixed step angle
 stepper motor rotates in steps in response to applied signals.
 mainly used for position control.
 used in disk drives, dot matrix printers, plotters and robotics and process control circuits
 Structure
 have permanent magnet called rotor (also called the shaft) surrounded by stator
 most common stepper motors have four stator windings that are paired with center-tap
 This type - commonly referred to as four-phase or unipolar stepper motor.
 center tap allows change of current direction in each of two coils when winding is
grounded, thereby resulting in polarity change of stator.
 Interfacing
 small stepper motor require current of 400 mA for its operation
 ports of microcontroller cannot source this much amount of current
 such motor - directly connected to ports, motor - draws large current from ports and damage it.
 suitable driver circuit is used to operate motor
 Motor Driver Circuit
 driver circuits are available readily in form of Ics
 LN2003 one such driver IC - High-Voltage High-Current Darlington transistor array, can give
current of 500mA.
 current is sufficient to drive small stepper motor.
 has protection diodes to protect motor from damage due to back emf and large eddy currents
 ULN2003 is used as driver to interface stepper motor to microcontroller
 Operation
 important parameter - step angle
 minimum angle through which motor rotates in response to each excitation pulse
 In four phase motor; 200 steps in one complete rotation then step angle is 360/200 = 1.8O
 to rotate we have to apply excitation pulse
 controller should send hexadecimal code through one of its ports
 hex code mainly depends on motor; motors do not have same code for their rotation
 E.g., let us consider hex code for motor to rotate in clockwise direction is 77H , BBH , DDH and
EEH.
 hex code will be applied to input of driver through assembly language program.
 To rotate stepper motor in anti-clockwise direction same code is applied in reverse order
Stepper Motor interface- Schematic Diagram
ASSEMBLY LANGUAGE PROGRAM
Main : MOV A, # 0FF H ; Initialization of Port 1
MOV P1, A ;
MOV A, #77 H ; Code for the Phase 1
MOV P1, A ;
ACALL DELAY ; Delay subroutine
MOV A, # BB H ; Code for the Phase II
MOV P1, A ;
ACALL DELAY ; Delay subroutine.
MOV A, # DD H ; Code for the Phase III
MOV P1, A ;
ACALL DELAY ; Delay subroutine
MOV A, # EE H ; Code for the Phase 1
MOV P1, A ;
ACALL DELAY ; Delay subroutine
SJMP MAIN; Keep the motor rotating continuously.
DELAY Subroutine
MOV R4, #0FF H ; Load R4 with FF
MOV R5, # 0FF ; Load R5 with FF
LOOP1: DJNZ R4, LOOP1 ; Decrement R4 until zero,wait
LOOP2: DJNZ R5, LOOP2 ; Decrement R5 until zero,wait
RET ; Return to main program
Stepper Motor interface - Schematic Diagram for (8085)
Detailed Connection diagram between 8085 and 8255
ASSEMBLY LANGUAGE PROGRAM (8085)
Main : MVI A, 80 ; 80H → Control word to configure PA,PB,PC in O/P
OUT CWR_Address ; Write control word in CWR of 8255
MVI A, 77 ; Code for the Phase 1
OUT PortA_Address ; sent to motor via port A of 8255 ;
CALL DELAY ; Delay subroutine
MVI A, BB ; Code for the Phase II
OUT PortA_Address ; sent to motor via port A of 8255
CALL DELAY ; Delay subroutine.
MVI A, DD ; Code for the Phase III
OUT PortA_Address ; sent to motor via port A of 8255;
CALL DELAY ; Delay subroutine
MVI A, EE H ; Code for the Phase 1
OUT PortA_Address ; sent to motor via port A of 8255 ;
CALL DELAY ; Delay subroutine
JMP MAIN ; Keep the motor rotating continuously.
DELAY Subroutine
MVI C, FF ; Load C with FF -- Change it for the speed variation
LOOP1: MVI D,FF ; Load D with FF
LOOP2: DCR D
JNZ LOOP2
DCR C
JNZ LOOP1
RET ; Return to main program
REFERENCES

 The 8051 Microcontroller and Embedded Systems Using Assembly and C


Muhammad Ali Mazidi, Janice Gillispie Mazidi, Rolin D. McKinlay
 https://www.electronicshub.org
 https://what-when-how.com/8051-microcontroller/
 https://www.pantechsolutions.net/
 https://www.tutorialspoint.com
 https://www.electronicwings.com/8051/

You might also like