Embedded system 8051 Microcontroller

307

Click here to load reader

Transcript of Embedded system 8051 Microcontroller

Page 1: Embedded system 8051 Microcontroller

ANKIT SHARMARESEARCH SCHOLAR

ME-VLSI DESIGNPEC UNIVERSITY OF

TECHNOLOGY CHANDIGARH-160012

INDIA

Page 2: Embedded system 8051 Microcontroller

EMBEDDED SYSTEM

Page 3: Embedded system 8051 Microcontroller

OUTLINES

INTRODUCTION TO COMPUTING Microprocessor Microcontroller 8051 Real World Interfacing of 8051

Page 4: Embedded system 8051 Microcontroller

INTRODUCTION TO COMPUTING

Page 5: Embedded system 8051 Microcontroller

DECIMAL AND BINARY NUMBER SYSTEMS

Human beings use base 10 (decimal) arithmetic There are 10 distinct symbols, 0, 1, 2, …,9

Computers use base 2 (binary) system There are only 0 and 1 These two binary digits are commonly referred to as

bits

Page 6: Embedded system 8051 Microcontroller

NUMBER SYSTEM

Decimal Binary Octal Hexa Decimal

Page 7: Embedded system 8051 Microcontroller

CONVERTING FROM DECIMAL TO BINARY Divide the decimal number by 2 repeatedly Keep track of the remainders Continue this process until the quotient becomes zero Write the remainders in reverse order to obtain the binary

number

Page 8: Embedded system 8051 Microcontroller

ANALOG VS DIGITAL

Page 9: Embedded system 8051 Microcontroller

POWER SUPPLY

Page 10: Embedded system 8051 Microcontroller

In general, we use an AC supply of 230V 50Hz, but this power has to be changed into required form or voltage range for providing power supply to different types of devices

Microcontrollers require a 5V DC supply, so AC 230V needs to be converted into 5V DC using the step-down converter in their power supply circuit.

Page 11: Embedded system 8051 Microcontroller

4 BASIC STEPS Step Down the Voltage Level Convert AC to DC Smoothing the Ripples using Filter Regulated IC

Page 12: Embedded system 8051 Microcontroller

STEP DOWN THE VOLTAGE LEVEL Step-down transformer consists of two windings, namely

primary and secondary windings. Primary can be designed using a less-gauge wire with more

number of turns as it is used for carrying low-current high-voltage power.

Secondary winding using a high-gauge wire with less number of turns as it is used for carrying high-current low-voltage power. Transformers works on the principle of Faraday’s laws of electromagnetic induction.

Actually, mutual induction between two or more winding is responsible for transformation action in an Electrical Transformer.

Page 13: Embedded system 8051 Microcontroller

CONVERT AC TO DC 230V AC power is converted into 12V AC (12V RMS), but

required power is 5V DC For this purpose, 12V AC power must be primarily converted

into DC power then it can be stepped down to the 5V DC. AC power can be converted into DC using Rectifier. There are different types of rectifiers, such as half-wave

rectifier, full-wave rectifier and bridge rectifier. Due to advantages of bridge rectifier over half & full wave

rectifier, bridge rectifier is frequently used for converting AC to DC.

Page 14: Embedded system 8051 Microcontroller

SMOOTHING THE RIPPLES USING FILTER

Output of diode bridge is a DC consisting of ripples also called pulsating DC.

pulsating DC can be filtered using an inductor filter or a capacitor filter or a resistor-capacitor-coupled filter for removing ripples.

Consider a capacitor filter which is frequently used in most cases for smoothing.

Page 15: Embedded system 8051 Microcontroller

Capacitor is an energy storing element. Capacitor stores energy while input increases from zero to a

peak value and, while supply voltage decreases from peak Value to zero, capacitor starts discharging.

This charging and discharging of the capacitor will make the pulsating DC into pure DC.

Page 16: Embedded system 8051 Microcontroller

REGULATING 12V DC INTO 5V DC USING VOLTAGE REGULATOR

15V DC voltage can be stepped down to 5V DC voltage using a DC step-down converter called as voltage reguIator IC7805.

The first two digits ‘78’ of IC7805 voltage regulator represent positive series voltage regulators and the last two digits ‘05’ represents the output voltage of the voltage regulator

Page 17: Embedded system 8051 Microcontroller

MICROPROCESSORS / CONTROLLERS

Page 18: Embedded system 8051 Microcontroller

WHY DO WE NEED TO LEARN

MICROPROCESSORS / CONTROLLERS The microprocessor is the core of computer systems Now a days many communication, digital entertainment,

portable devices, are controlled by them. A designer should know what types of components he

needs, ways to reduce production costs and product reliable.

Page 19: Embedded system 8051 Microcontroller

DIFFERENT ASPECTS OF A MICROPROCESSOR /

CONTROLLER Hardware :Interface to the real world

Software :Order how to deal with inputs

Page 20: Embedded system 8051 Microcontroller

THE NECESSARY TOOLS FOR A MICROPROCESSOR / CONTROLLER

CPU: Central Processing Unit I/O: Input /Output Bus: Address bus , Control Bus & Data bus Memory: RAM & ROM Timer Interrupt Serial Port Parallel Port

Page 21: Embedded system 8051 Microcontroller

MICROPROCESSOR:

Multipurpose Re-Programmable Digital Device Semiconductor IC

Page 22: Embedded system 8051 Microcontroller

MICROPROCESSOR (CONT.)

Works On:Input data from outer world

Process it under control of stored instructions /program

in memory.

Provide desired result to the outer world.

Page 23: Embedded system 8051 Microcontroller

MICROCONTROLLER Introduced in 1981 by Intel Corporation. Microcontroller is a programmable digital processor

with necessary peripherals. Both microcontrollers and microprocessors are complex

sequential digital circuits meant to carry out job according to the program / instructions.

Page 24: Embedded system 8051 Microcontroller

GENERAL PURPOSE MICROPROCESSORS

No RAM No ROM No I/O ports Many chips on mother’s board

A single chip

Page 25: Embedded system 8051 Microcontroller

MICROCONTROLLER

CPU (microprocessor) RAM ROM I/O ports Timer ADC and other peripherals

Page 26: Embedded system 8051 Microcontroller

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

Page 27: Embedded system 8051 Microcontroller

DISADVANTAGES OF MICROPROCESSOR The overall system cost is high A large sized PCB is required for assembling all the

components Overall product design requires more time Physical size of the product is big A discrete components are used, the system is not reliable

Page 28: Embedded system 8051 Microcontroller

ADVANTAGES OF MICROCONTROLLER BASED SYSTEM

As the peripherals are integrated into a single chip, the overall system cost is very less

The product is of small size compared to micro processor based system

The system design now requires very little efforts As the peripherals are integrated with a microprocessor the

system is more reliable Though microcontroller may have on chip ROM,RAM and I/O

ports, additional ROM, RAM I/O ports may be interfaced externally if required

On chip ROM provide a software security

Page 29: Embedded system 8051 Microcontroller

MICROCONTROLLER The fixed amount of on-chip ROM, RAM, and number of I/O

ports makes them ideal 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

Page 30: Embedded system 8051 Microcontroller

8051 FAMILY HAS LARGEST NUMBER OF DIVERSIFIED (MULTIPLE SOURCE) SUPPLIERS

Intel Atmel Philips/ Signetics AMD Infineon (formerly Siemens) Matra Dallas Semiconductor/Maxim

Page 31: Embedded system 8051 Microcontroller

EMBEDDED SYSTEMS

Embedded system means the processor is embedded into that application.

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

Page 32: Embedded system 8051 Microcontroller

It has RAM memory and an operating system that loads a variety of applications into RAM and lets the CPU run them

PC contains or is connected to various embedded products Each one peripheral has a microcontroller inside it that

performs only one task In an embedded system, there is only one application

software that is typically burned into ROM. Example : Printer, keyboard, Video game player

Page 33: Embedded system 8051 Microcontroller

Home Appliances, intercom, telephones, security systems,

garage door openers, answering machines, fax machines, home computers, TVs, cable TV tuner, VCR, camcorder, remote controls, video games, cellular phones, musical instruments, sewing machines, lighting control, paging, camera, pinball machines, toys, exercise equipment

Office Telephones, computers, security systems, fax

machines, microwave, copier, laser printer, color printer, paging

Auto Trip computer, engine control, air bag, ABS,

instrumentation, security system, transmission control, entertainment, climate control, cellular

phone, keyless entry

Page 34: Embedded system 8051 Microcontroller

CHOOSING A MICROCONTROLLER 8-bit microcontrollers

Motorola’s 6811 Intel’s 8051 Zilog’s Z8 Atmel Microchip’s PIC

There are also 16-bit & 32-bit Uc made by various chip makers

Page 35: Embedded system 8051 Microcontroller

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 higher performance or lower power

consumption Versions, software development tools, such as compilers, assemblers,

simulator and debuggers Cost per unit

Page 36: Embedded system 8051 Microcontroller

COMPARISON OF THE 8051 FAMILY MEMBERS

ROM type 8031 no ROM 80xx mask ROM 87xx EPROM 89xx Flash EEPROM

89xx 8951 8952 8953 8955

898252 891051 892051

Example (AT89C51,AT89LV51) AT= ATMEL(Manufacture) C = CMOS technology LV= Low Power(3.0v)

Page 37: Embedded system 8051 Microcontroller

OVERVIEW OF 8051 FAMILY

Page 38: Embedded system 8051 Microcontroller

INTEL INTRODUCED 8051, REFERRED AS MCS- 51, IN 1981

The 8051 is an 8-bit processor The CPU can work on only 8 bits of data at a time 128 bytes of RAM 4K bytes of on-chip ROM Two 16 bit timers One serial port Internal memory consists of on-chip ROM and on-chip data RAM Separate memory space for programs (code) and data

Page 39: Embedded system 8051 Microcontroller

Four I/O ports, each 8 bits wide 6 interrupt sources Full duplex UART On-chip clock oscillator 64K external code & data memory space. 210 bit-addressable locations. Operating frequency is 24MHz-33MHz +5V Regulated DC power supply is required to operate .

Page 40: Embedded system 8051 Microcontroller

8051 INTERNAL BLOCK DIAGRAM

Page 41: Embedded system 8051 Microcontroller

MOST WIDELY USED REGISTERS

A (Accumulator) For all arithmetic and logic instructions

B, R0, R1, R2, R3, R4, R5, R6, R7 DPTR (data pointer), and PC (program

counter) SP(stack pointer)

A

B

R0

R1

R3

R4

R2

R5

R7

R6

DPH DPL

PC

DPTR

PC

Some 8051 16-bit Register

Some 8-bitt Registers of the 8051

Page 42: Embedded system 8051 Microcontroller

ACCUMULATOR

Accumulator, as its name suggests, is used as a general register to accumulate the results of a large number of instructions.

For example, if you want to add the number 10 and 20, the resulting 30 will be stored in Accumulator. Once you have a value in Accumulator you may continue processing value or you may store it in another register or in memory.

Page 43: Embedded system 8051 Microcontroller

THE "R" REGISTERS

The "R" registers are a set of eight registers that are named R0, R1, etc. up to and including R7.

Example:-MOV A,R3 ;Move the value of R3 into the accumulatorADD A,R4 ;Add the value of R4MOV R5,A ;Store the resulting value temporarily in R5

Page 44: Embedded system 8051 Microcontroller

THE "B" REGISTER The "B" register is very similar to the Accumulator in the

sense that it may hold an 8-bit (1-byte) value. The "B" register is only used by two 8051 instructions: MUL

AB and DIV AB. Thus, if you want to quickly and easily multiply or divide A by another number, you may store other number in "B" and make use of these two instructions.

Aside from the MUL and DIV instructions, "B" register is often used as yet another temporary storage register much like a ninth "R" register.

Page 45: Embedded system 8051 Microcontroller

PROGRAM COUNTER(PC) The Program Counter (PC) is a 2-byte address. Indicate, where next instruction to execute is found in

memory. This means that it can access program addresses 0000 to

FFFFH, a total of 64K bytes of code The first opcode is burned into ROM address 0000H, since

this is where the 8051 looks for the first instruction when it is booted. PC incremented each time an instruction is executed.

We achieve this by the ORG statement in the source program

PC is not always incremented by one. Some instructions need 2 or 3 bytes PC will be incremented by 2 or 3 in these cases.

Page 46: Embedded system 8051 Microcontroller

DPTR The Data Pointer (DPTR) is the 8051s only user-access 16-

bit (2-byte) register. DPTR, is used to point to data. It is used by number of

commands which allow the 8051 to access external memory. When the 8051 accesses external memory it will access external memory at the address indicated by DPTR.

While DPTR is most often used to point to data in external memory, many programmers often take advantage of the fact that its the only true 16-bit register available. It is often used to store 2-byte values which have nothing to do with memory locations.

Page 47: Embedded system 8051 Microcontroller

STACK IN 8051 Section of RAM used to store

information temporarily Could be data or an address CPU needs this storage area since

there are only limited number of registers

The register used to access the stack is called SP (stack pointer) register.

The stack pointer in the 8051 is only 8 bits wide, which means that it can take value 00 to FFH. When 8051 powered up, the SP register contains value 07h by default .

7FH

30H

2FH

20H1FH

17H10H0FH

07H08H

18H

00HRegister Bank 0

(Stack )Register Bank 1

Register Bank 2

Register Bank 3

Bit-Addressable RAM

Scratch pad RAM

Page 48: Embedded system 8051 Microcontroller

STACK POINTER(SP)

The Stack Pointer is used to indicate where the next value to be removed from the stack should be taken from.

When you push a value onto the stack, the 8051 first increments the value of SP and then stores the value at the resulting memory location.

When you pop a value off the stack, the 8051 returns value from the memory location indicated by SP, and then decrements the value of SP.

Page 49: Embedded system 8051 Microcontroller

When the 8051 is initialized SP will be initialized to 07h. If you immediately push a value onto the stack, the value

will be stored in Internal RAM address 08h. First the 8051 will increment the value of SP (from 07h to

08h) and then will store the pushed value at that memory address (08h)

SP is modified directly by the 8051 by six instructions: PUSH, POP, ACALL, LCALL, RET, and RETI.

Page 50: Embedded system 8051 Microcontroller

PROGRAM STATUS WORD Program status word (PSW) register, also referred to as 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 instruction was executed

The PSW3 and PSW4 are designed as RS0 and RS1, and are used to change the bank

The two unused bits are user-definable

Page 51: Embedded system 8051 Microcontroller

PROGRAM STATUS WORD

Bits of the PSW Register

Page 52: Embedded system 8051 Microcontroller

INSTRUCTIONS THAT

AFFECT FLAG BITS

Instruction CY OV ACADD X X XADDC X X XSUBB X X XMUL O XDIV O XDA XRPC XPLC XSETB C 1CLR C OCPL C XANL C,bit XANL C, /bit XORL C, bit XORL C, /bit XMOV c, bit XCJNE X

Page 53: Embedded system 8051 Microcontroller

EXAMPLE-ADD INSTRUCTION & PSW Flag bits affected by ADD instruction are CY, P, AC, and OV Show status of CY, AC and P flag after addition of 38H &

2FH in following instructions. MOV A, #38H ADD A, #2FH ;after the addition A=67H, CY=0

Solution: 38 (00111000) + 2F(00101111)= 67 (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 Accumulator has an odd number of 1s (it has five 1s)

Page 54: Embedded system 8051 Microcontroller

8051 PINS FUNCTIONING

Page 55: Embedded system 8051 Microcontroller

PIN DESCRIPTION OF 8051

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)

Page 56: Embedded system 8051 Microcontroller

QFP(quad flat package)

LLC(leadless chip carrier)

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

Page 57: Embedded system 8051 Microcontroller

PIN DESCRIPTION (CONT’)

Page 58: Embedded system 8051 Microcontroller

PIN DIAGRAM-8051

Page 59: Embedded system 8051 Microcontroller

VCC )40( & GND )20(

VCC ( pin 40 ) Vcc provides supply voltage to the chip. The voltage source is +5V.

GND ( pin 20 ): ground

Page 60: Embedded system 8051 Microcontroller

OSCILLATOR CIRCUIT:- The 8051 requires an external oscillator circuit. The oscillator circuit usually runs around 12MHz. The crystal generates 12M pulses in one second. The pulse is used to synchronize the system operation in a

controlled pace. Used for synchronizing internal operations. Pins XTAL1 & XTAL2 have been used. Length of machine cycle depends on the frequency of crystal

oscillator connected to 8051.

Page 61: Embedded system 8051 Microcontroller

XTAL1 AND XTAL2 (PIN 18 & PIN 19 ) 8051 has on-chip oscillator but requires external clock to run

it A quartz crystal oscillator is connected to inputs XTAL1

(pin19) and XTAL2 (pin18) Quartz crystal oscillator needs two capacitors of 30 pF

value

Page 62: Embedded system 8051 Microcontroller

RST ( PIN 9 ) 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

Page 63: Embedded system 8051 Microcontroller

RESET VALUE OF SOME 8051 REGISTERS:Register Reset Value

PC 0000

DPTR 0000

ACC 00

PSW 00

SP 07

B 00

P0-P3 FF

RAM are all zero.

Page 64: Embedded system 8051 Microcontroller

In order for the RESET input to be effective, it must have 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

Page 65: Embedded system 8051 Microcontroller

( PIN 31 ) External access, is an input pin and must be connected to

Vcc or GND “ ” means active low

The 8051 family members all come with on-chip ROM to store programs EA pin is connected to Vcc

The 8031 and 8032 family members do no have on-chip ROM, so code is stored on an external ROM and is fetched by 8031/32 EA pin must be connected to GND to indicate that the code

is stored externally

Page 66: Embedded system 8051 Microcontroller

( PIN 29 ) & ALE ( PIN 30 ) Following two pins are used mainly in 8031-based systems : Program store enable, is an output pin

This pin is connected to OE pin of the ROM ALE :Address latch enable, is output pin and is active high & ALE are used for external ROM The 8031 multiplexes address and data through port 0 to save

pins ALE pin is used for de multiplexing the address and data

Page 67: Embedded system 8051 Microcontroller

I/O PORT PINS The four 8-bit I/O ports P0, P1, P2 and P3 each uses 8 pins All the ports upon RESET are configured as output, ready to

be used as input ports P1, P2, and P3 have internal pull-up resisters.

P1, P2, and P3 are not open drain. P0 has no internal pull-up resistors and does not connects to

Vcc inside the 8051. P0 is open drain

Page 68: Embedded system 8051 Microcontroller

PORT 0 Port 0 is also designated as AD0-AD7,

allowing it to be used for both address and data When connecting an 8051/31 to an

external memory, port 0 provides both address and data

The 8051 multiplexes address and data through port 0 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

Page 69: Embedded system 8051 Microcontroller

PORT 0 (CONT’) Port 0 is 8-bitbidirectional I/O port. Port 0 pins can be used as high-impedance inputs. P0 pin must be connected externally to 10K ohm pull-up

resistor P0 is an open drain, unlike P1, P2, and P3 Open drain is used for MOS chips in same way that open

collector is used for TTL chips For output, pin latches are programmed to 0. For input, pin latches are programmed to 1

Page 70: Embedded system 8051 Microcontroller

PORT 1 & PORT 2 Port 1 & Port 2 is an 8-bit bidirectional I/0 port. In 8051 with no external memory connection

Both P1 and P2 are used as simple I/O In 8031/51external memory connections

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

For output, pin latches are programmed to 0. For input, pin latches are programmed to 1.

Page 71: Embedded system 8051 Microcontroller

PORT 3 Port 3 is an 8-bit bi-directional I/0 port. Port 3 does not need any pull-up resistors Port 3 has the additional function of providing some

extremely important signals

Page 72: Embedded system 8051 Microcontroller

PORT 3 (CONT’)P3 Bit Function Pin

P3.0 RxD 10

P3.1 TxD 11

P3.2 12

P3.3 13

P3.4 T0 14

P3.5 T1 15

P3.6 16

P3.7 17

RXD (P3.0): Serial input port TXD (P3.1): Serial output port INT0 (P3.2): External interrupt INT1 (P3.3): External interrupt T0 (P3.4): Timer 0 external input T1 (P3.5): Timer 1 external input WR (P3.6): External data memory write

strobe RD (P3.7): External data memory read

strobe

Page 73: Embedded system 8051 Microcontroller

INTERRUPTS

Page 74: Embedded system 8051 Microcontroller

INTERRUPTS 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 using

interrupts Whenever any device needs its service, the device notifies

microcontroller by sending it an interrupt signal Upon receiving an interrupt signal, Microcontroller interrupts

whatever it is doing and serves device Program associated with Interrupt is called interrupt service

routine (ISR) or interrupt handler

Page 75: Embedded system 8051 Microcontroller

INTERRUPT SERVICE ROUTINE For every interrupt, there must be an interrupt service

routine (ISR), or interrupt handler When interrupt is invoked, microcontroller runs 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

Page 76: Embedded system 8051 Microcontroller

STEPS IN EXECUTING AN INTERRUPT Upon activation of interrupt, microcontroller perform these

steps It finishes the instruction it is executing and saves the address

of the next instruction (Program Counter) on the stack using PUSH operation.

It also saves current status of all interrupts internally (i.e : not on stack)

It jumps to a fixed location in memory, called interrupt vector table, that holds address of the ISR

Page 77: Embedded system 8051 Microcontroller

Microcontroller gets address of ISR from interrupt vector table and jumps to it

It starts to execute the interrupt service subroutine until it reaches the last instruction of subroutine which is RETI (return from interrupt)

Upon executing RETI instruction, microcontroller returns to the place where it was interrupted First, it gets program counter (PC) address from stack by

popping the top two bytes of the stack into PC Then it starts to execute from that address

Page 78: Embedded system 8051 Microcontroller

SIX INTERRUPTS IN 8051

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 external hardware interrupts INT0 , & INT1 Serial communication has a single interrupt that belongs to

both receive and transfer

Page 79: Embedded system 8051 Microcontroller

INTERRUPT VECTOR TABLE

ORG 00h ;wake-up ROM reset

locationLJMP MAIN ;By-pass interrupt

vector table

ORG 30HMAIN:....END

Page 80: Embedded system 8051 Microcontroller

ENABLING AND DISABLING AN INTERRUPT Upon reset, all interrupts are disabled (masked), means 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

Page 81: Embedded system 8051 Microcontroller

IE (INTERRUPT ENABLE) REGISTER

Page 82: Embedded system 8051 Microcontroller

ENABLING AND DISABLING AN INTERRUPT

To enable an interrupt, we take the following steps: 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

Page 83: Embedded system 8051 Microcontroller

EXAMPLE Show instructions to (a) enable serial interrupt, timer 0

Interrupt, and external hardware interrupt 1 (ex1) (b) disable (Mask) timer 0 interrupt (c) show how to disable all Interrupts with a single instruction.

Solution:(A) MOV IE, #10010110B ; Timer 0, EX1 &

; enable serialAnother way

Setb IE.7 ;EA=1, global enableSetb IE.4 ;enable serial interruptSetb IE.1 ;enable timer 0 interruptSetb IE.2 ;enable EX1

(B) CLR IE.1 ;mask (disable) timer

0 interrupt only(C) CLR IE.7 ;disable all

interrupts

Page 84: Embedded system 8051 Microcontroller

The timer flag (TF) is raised when timer rolls over If timer interrupt in IE register is enabled, whenever timer

rolls over, TF is raised, and microcontroller is interrupted in whatever it is doing, and jumps to the interrupt vector table to service the ISR

In this way, microcontroller can do other until it is notified that the timer has rolled over

Page 85: Embedded system 8051 Microcontroller

EXTERNAL HARDWARE INTERRUPTS 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

Page 86: Embedded system 8051 Microcontroller

LEVEL TRIGGERED INTERRUPT

In 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

execution of the last instruction of ISR, RETI; otherwise, another interrupt will be generated

This is called a level-triggered or level activated interrupt and is default mode upon reset of the 8051

Page 87: Embedded system 8051 Microcontroller

EXAMPLE

Assuming that INT1 pin is connected to a switch that is normally high. Whenever it goes low, it should turn on an LED. LED is normally off. When it is turned on it should stay on for a fraction of a second. Till the time switch is pressed low, LED should stay on.

Page 88: Embedded system 8051 Microcontroller

Solution:1.Org 0000h ;Starting point2.LJMP MAIN ;by-pass interrupt vector table ISR to turn on LED

Org 0013h ;int1 ISR pin3.1=INT1 Setb P1.3 ;turn on LED Mov r3,#255 BACK: DJNZ R3,BACK ;keep LED on for a while Clr p1.3 ;turn off the LED RETI ;return from ISR MAIN program for initialization

3.Org 30h ;from 00 -> 30h to avoid interrupt rom location4.MAIN: MOV IE,#10000100B ;enable external INT 15.HERE: SJMP HERE ;stay here until get interrupted End

Page 89: Embedded system 8051 Microcontroller

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 hardware interrupts in the IE register are enabled, the controller keeps check intn pin for a low-level signal once each machine cycle

According to one manufacturer’s data sheet, pin must be held in a low state until the start of the execution of ISR . if intn pin is brought back to a logic high before start of execution of ISR there will be no interrupt

If INT pin is left at a logic low after RETI instruction of ISR, another interrupt will be activated after one instruction is executed

Page 90: Embedded system 8051 Microcontroller

SERIAL COMMUNICATION INTERRUPTRI and TI Flags and Interrupts

Page 91: Embedded system 8051 Microcontroller

SERIAL COMMUNICATION INTERRUPT TI (transfer interrupt) is raised when last bit of the

framed data, stop bit, is transferred, indicating that SBUF register is ready to transfer the next byte

RI (received interrupt) is raised when entire frame of data, including stop bit, is received In other words, when the SBUF register has a byte, RI is

raised to indicate that received byte needs to be picked up before it is lost (overrun) by new incoming serial data

Page 92: Embedded system 8051 Microcontroller

In 8051, one interrupt set aside for serial communication This interrupt is used for both send and receive data Interrupt bit in IE register (IE.4) is enabled, when RI or TI is

raised 8051 gets interrupted and jumps to memory location

0023H To execute ISR we must examine TI and RI flags to see

which one caused the interrupt and respond accordingly

Page 93: Embedded system 8051 Microcontroller

USE OF SERIAL COM IN 8051

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

Page 94: Embedded system 8051 Microcontroller

INTERRUPT PRIORITY

When 8051 is powered up, priorities are assigned according to the following

Highest To Lowest PriorityExternal Interrupt 0 (INT0)Timer Interrupt 0 (TF0)External Interrupt 1 (INT1)Timer Interrupt 1 (TF1)Serial Communication (R1+T1)

Page 95: Embedded system 8051 Microcontroller

INTERRUPT PRIORITY (CONT’) 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 interrupts, we make corresponding bit in the IP register high

When two or more interrupt bits in IP register are set to high While these interrupts have a higher priority than others, they

are serviced according to the sequence

Page 96: Embedded system 8051 Microcontroller

INTERRUPT PRIORITY REGISTER (BIT-ADDRESSABLE)

Priority bit=1 assigns high priority Priority bit=0 assigns low priority

Page 97: Embedded system 8051 Microcontroller

PROGRAMMING TIMERS

Page 98: Embedded system 8051 Microcontroller

PROGRAMMING TIMERS

8051 has two timers/counters, they can be used either as Timers to generate a time delay or as Event counters to count events happening outside

microcontroller Both timer 0 and timer 1 are 16 bits wide since 8051 has an

8-bit architecture, each 16-bits timer is accessed as two separate registers of low byte and high byte

Page 99: Embedded system 8051 Microcontroller

TIMER 0 & TIMER 1

Accessed as low byte and high byte Low byte register is called TL0/TL1 High byte register is called TH0/TH1

Accessed like any other register Mov TL0, #4FH Mov R5, TH0

Page 100: Embedded system 8051 Microcontroller

TMOD REGISTER Both timers 0 and 1 use same register, called TMOD

(timer mode), to set various timer operation modes TMOD is a 8-bit register,

Lower 4 bits are for timer 0 Upper 4 bits are for timer 1

In each case, The lower 2 bits are used to set timer mode The upper 2 bits to specify operation

Page 101: Embedded system 8051 Microcontroller

--- --- --- X X X X X x x x x x x x x

Page 102: Embedded system 8051 Microcontroller

EXAMPLE Indicate which mode and which timer are selected for each of

the following. (a) MOV TMOD, #01H (b) MOV TMOD, #20H (c) MOV TMOD,

#12H Solution:

We convert the value from hex to binary. we have: (a) TMOD = 00000001, mode 1 of timer 0 is selected. (b) TMOD = 00100000, mode 2 of timer 1 is selected. (c) TMOD = 00010010, mode 2 of timer 0, and mode 1 of timer 1

are selected.

Page 103: Embedded system 8051 Microcontroller

TMOD REGISTER-GATE Timers of 8051 do starting and stopping by either software or

hardware control In using software to start and stop timer where GATE=0

The start and stop of the timer are controlled by way of software by TR (timer start) bits TR0 and TR1

The SETB instruction starts it, and it is stopped by CLR instruction These instructions start and stop timers as long as GATE=0 in TMOD register

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

Page 104: Embedded system 8051 Microcontroller

EXAMPLE Find timer’s clock frequency and its period for various 8051-

based system, with crystal frequency 11.0592 MHz when C/T bit of TMOD is 0. 1/12 × 11.0529 MHz = 921.6 MHz; T = 1/921.6 kHz = 1.085 us

Page 105: Embedded system 8051 Microcontroller

EXAMPLE Find value for TMOD if we want to

program timer 0 in mode 2, use 8051 XTAL for clock source, and use instructions to start and stop timer. TMOD = 0000 0010

Page 106: Embedded system 8051 Microcontroller

TIMER MODE 1

Page 107: Embedded system 8051 Microcontroller

MODE 1 PROGRAMMING The following are the characteristics and operations of

mode1:1. It is a 16-bit timer;

Allows value of 0000 to FFFFH to be loaded into timer’s register TL and TH

2. 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 13. After the timer is started, it starts to count up

It counts up until it reaches its limit of FFFFH

Page 108: Embedded system 8051 Microcontroller

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, & 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 instructions CLR TR0 or CLR TR1, for timer 0 and timer 1, respectively

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

Page 109: Embedded system 8051 Microcontroller

GENERATE A TIME DELAY Load the TMOD value register indicating which timer(timer 0 or timer 1 )is to be

used and which 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 become high

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

Page 110: Embedded system 8051 Microcontroller
Page 111: Embedded system 8051 Microcontroller

COUNTER

Page 112: Embedded system 8051 Microcontroller

Timers can also be used as counters counting events happening outside the 8051

Page 113: Embedded system 8051 Microcontroller

C/T BIT IN TMOD REGISTER 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

ulses 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)

Page 114: Embedded system 8051 Microcontroller

MEMORY

Page 115: Embedded system 8051 Microcontroller

MEMORY CAPACITY

Number of bits that a semiconductor memory chip can store is called chip capacity Units of Kbits (kilobits), Mbits (megabits), and so on

Distinguished from storage capacity of computer systems Memory capacity of a memory IC chip is always given bits,

memory capacity of a computer system is given in bytes 16M memory chip – 16 megabits Computer comes with 16M memory – 16 megabytes

Page 116: Embedded system 8051 Microcontroller

MEMORY ORGANIZATION Memory chips are organized into number of locations within

IC Each location can hold 1 bit, 4 bits, 8 bits, or even 16 bits,

depending on how it is designed internally Number of locations within a memory IC depends on

the address pins Number of bits that each location can hold is always

equal to the number of data pins A memory chip contain 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 .y bits

Page 117: Embedded system 8051 Microcontroller

SPEED One of the important feature 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

Shorter this elapsed time, the better, and consequently, the more expensive the memory chip

Speed of memory chip is referred to as its access time

Page 118: Embedded system 8051 Microcontroller

SPEED (CONT’) 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 ( = 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.

Page 119: Embedded system 8051 Microcontroller

Example A 512K memory chip has 8 pins for data.

Find: (a) The organization (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 number of locations within this memory chip, divide the capacity by 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 = 64K

Page 120: Embedded system 8051 Microcontroller

TYPES OF MEMORY

Page 121: Embedded system 8051 Microcontroller

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 non volatile memory There are different types of read-only memory

PROM EPROM EEPROM Flash EPROM Mask ROM

Page 122: Embedded system 8051 Microcontroller

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

Page 123: Embedded system 8051 Microcontroller

EPROM (ERASABLE PROGRAMMABLE ROM) (CONT’) To program a UV-EPROM chip, 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, 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

Page 124: Embedded system 8051 Microcontroller

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

Page 125: Embedded system 8051 Microcontroller

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 ( = 16K)

Page 126: Embedded system 8051 Microcontroller

EEPROM (ELECTRICALLY ERASABLE PROGRAMMABLE ROM) EEPROM has several advantage over EPROM

Its method of erasure is electrical and therefore instant, as opposed to the 20- minute 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

Page 127: Embedded system 8051 Microcontroller

FLASH MEMORY EPROM Flash EPROM has become a popular user-programmable

memory chip Process of erasure of the entire contents takes less than a

second, or might say in a flash The erasure method is electrical

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

Page 128: Embedded system 8051 Microcontroller

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

Page 129: Embedded system 8051 Microcontroller

MASK ROM Mask ROM refers to a kind of ROM in which the contents are

programmed by the IC manufacturer, not user programmable 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

Page 130: Embedded system 8051 Microcontroller

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

There are three types of RAM Static RAM (SRAM) NV-RAM (nonvolatile RAM) Dynamic RAM (DRAM)

Page 131: Embedded system 8051 Microcontroller

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 high capacity SRAM, but its capacity is far below DRAM

Page 132: Embedded system 8051 Microcontroller

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

Page 133: Embedded system 8051 Microcontroller

DRAM (DYNAMIC RAM) Dynamic RAM uses a capacitor to store each bit

It cuts down 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

Page 134: Embedded system 8051 Microcontroller

PACKING ISSUE IN DRAM In DRAM there is a problem of packing a large number of cells

into a single chip with 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

Page 135: Embedded system 8051 Microcontroller

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

Page 136: Embedded system 8051 Microcontroller

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

Page 137: Embedded system 8051 Microcontroller

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

Page 138: Embedded system 8051 Microcontroller

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), hich must be activated for the memory’s contents to be accessed

Sometimes the chip select is also referred to as chip enable (CE)

Page 139: Embedded system 8051 Microcontroller

MEMORY ADDRESS DECODING (CONT’) In connecting a memory chip to 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

Page 140: Embedded system 8051 Microcontroller

INTERNAL MEMORY OF 8051 8051 implements a separate memory space for programs (code),

data & and external RAM. Both code and data may be internal, however, both expand using

external components to a maximum of 64K code memory and 64K data memory.

Internal memory consists of on-chip ROM and on-chip data RAM. This is refereed to as a Harvard architecture.

The early Mark I (1944) computer developed at Harvard was of this type of architecture.

Von Neumann at Princeton pointed out that it was not necessary to put instructions and data in separate memories. Most machines have been Princeton architecture.

Page 141: Embedded system 8051 Microcontroller

On-chip RAM contains a rich arrangement of general purpose storage, bit addressable storage, register banks, and special function registers.

Registers and input/output ports are memory mapped and accessible like any other memory location.

Stack resides in internal RAM, rather than in external RAM. The internal data memory is accessed using an 8-bit address.

Page 142: Embedded system 8051 Microcontroller

ROM MEMORY MAP IN 8051 FAMILY

Page 143: Embedded system 8051 Microcontroller

RAM MEMORY SPACE ALLOCATION IN 8051 UC

Page 144: Embedded system 8051 Microcontroller

REGISTER BANKS IN 8051 MICROCONTROLLER

Page 145: Embedded system 8051 Microcontroller

SPECIAL FUNCTION REGISTERS ACC B PSW SP DPTR IP PMODE PCON TMODE TCON etc.

Page 146: Embedded system 8051 Microcontroller

SPECIAL FUNCTION REGISTERS 8051 has 21 special function registers (SFR) at the top of

internal RAM from address 80H to FFH. Most of the addresses from 80H to FFH are not defined,

except for 21 of them. Some SFR’s are both bit-addressable and byte-addressable,

depending on the instruction accessing the register. All 8051 CPU registers, I/O ports, timers and other

architecture components are accessible in 8051 C through SFRs

Page 147: Embedded system 8051 Microcontroller

SFR REGISTERS AND THEIR ADDRESSES The SFR (Special Function Register) can be accessed by

their names or by their addresses MOV 0E0H,#55H ;is the same as MOV A,#55h ;load 55H into A MOV 0F0H,R0 ;is the same as MOV B,R0 ;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

Page 148: Embedded system 8051 Microcontroller

SFR REGISTERSAND THEIRADDRESSES(CONT’)

F8 FFF0 B F7E8 EFE0 Acc E7D8 DFD0 PSW D7C8 CFC0 C7B8 IP BFB0 P3 B7A8 IE AFA0 P2 A798 SCON SBUF 9F90 P1 9788 TCON TMOD TL0 TL1 TH0 TH1 8F80 P0 SP DPL DPH PCON 87

Page 149: Embedded system 8051 Microcontroller

SFR REGISTERS AND THEIR ADDRESSES

Page 150: Embedded system 8051 Microcontroller

Write code to send 55H to ports P1 and P2, using (a) their names (b) their addresses Solution : (a) MOV A,#55H ;A=55H MOV P1,A ;P1=55H MOV P2,A ;P2=55H (b) From Table 5-1, P1 address=80H; P2 address=A0H MOV A,#55H ;A=55H MOV 80H,A ;P1=55H MOV 0A0H,A ;P2=55H

Page 151: Embedded system 8051 Microcontroller

B REGISTER

B register is used along with the accumulator for multiply and divide operations. MUL AB: multiplies 8 bit unsigned values in A and B. and

leaves the 16 bit result in A (low byte) and B (high byte). DIV AB: divided A by B, leaving the integer result in A and

remainder in B. B register is bit-addressable.

Page 152: Embedded system 8051 Microcontroller

PSW (PROGRAM STATUS WORD) / FLAG REGISTER

Page 153: Embedded system 8051 Microcontroller

STACK POINTER Stack pointer (SP) is an 8-bit register at

address 81H. Register used to access stack is called SP

(stack pointer) register. Stack pointer in 8051 is 8 bits wide, it can

take value 00 to FFH. When 8051 powered up, SP register contains

value 07. It contains address of data item currently on

top of the stack. Stack operations include pushing data on

stack and popping data off stack.

Page 154: Embedded system 8051 Microcontroller

Pushing increments SP before writing data. Popping from stack reads data and decrements SP. 8051 stack is kept in the internal RAM. Depending on the initial value of the SP, stack can have

different sizes Example: MOV SP,#5FH

On 8051 this would limit the stack to 32 bytes since the uppermost address of on chip RAM is 7FH.

Page 155: Embedded system 8051 Microcontroller

DATA POINTER (DPTR) Data pointer (DPTR): is used to access external data or

code. DPTR is a 16 bit register at addresses 82H (low byte) and

83H (high byte). The data pointer is used in operations regarding external

RAM and some instructions involving code memory. Example: the following instructions write 55H into

external RAM location 1000H: MOV A,#55H MOV DPTR,#1000H MOVX @DPTR,A

Page 156: Embedded system 8051 Microcontroller

LCD INTERFACING

WITH

MICROCONTROLLER

16X2 LCD

Page 157: Embedded system 8051 Microcontroller

ADDRESSING MODE OF 8051

Page 158: Embedded system 8051 Microcontroller

The CPU can access data in various ways, which are called addressing modes Immediate Addressing Mode Register Addressing Mode Direct Addressing Mode Register indirect Addressing Mode Indexed Addressing Mode

Addressing modes

ImmediateAddressing

RegisterAddressing

DirectAddressing

Register indirectAddressing

IndexedAddressing

Page 159: Embedded system 8051 Microcontroller

1- IMMEDIATE ADDRESSING MODE The source operand is a constant

The immediate data must be preceded by 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 Operand comes immediately after op-code

Page 160: Embedded system 8051 Microcontroller

EXAMPLES OF IMMEDIATE ADDRESSING MODE

MOV A,#25H // load 25H into A MOV R4,#62 // load 62 into R4 MOV B,#40H // load 40H into B MOV DPTR,#4521H // DPTR=4512H MOV DPL,#21H // This is the same MOV DPH,#45H // as above MOV DPTR,#68975 //illegal!! Value > 65535 (FFFFH)

Page 161: Embedded system 8051 Microcontroller

We can use EQU directive to access immediate data

We can also use immediate addressing mode to send data to 8051 ports

Count EQU 30... ...MOV R4,#COUNT // R4=1EH

MOV P1,#55H // Sending

data to port

Page 162: Embedded system 8051 Microcontroller

2- REGISTER ADDRESSING MODE Register addressing mode involves the use of registers to

hold the data to be manipulated MOV A, R0 // copy the contents of R0 in to A. MOV R1, A // copy the contents of A in to R1. ADD A,R5 // add the content of R5 to content

of A. The movement of data between Rn registers is not allowed

MOV R4,R7 // Invalid Command The source and destination registers must match in size

MOV DPTR,A // Error

Page 163: Embedded system 8051 Microcontroller

3- DIRECT ADDRESSING MODE In direct addressing mode, the data is in a RAM memory

location whose address is known, and this address is given as a part of the instruction.

Contrast this with the immediate addressing mode in which the operand itself is provided with the instruction. MOV R0,40H ;save content of 40H memory location in

R0 MOV 56H,A ;save content of A in 56H MOV PSW,R5 ; M(PSW) R5

Page 164: Embedded system 8051 Microcontroller

It is most often used direct addressing mode to access RAM locations 30 – 7FH The entire 128 bytes of RAM can be accessed The register bank locations are accessed by the register

names MOV A,R4 ;which means copy R4 into A

Page 165: Embedded system 8051 Microcontroller

PUSH/POP WITH DIRECT ADDRESSING MODE Only direct addressing mode is allowed for pushing or popping the stack

PUSH A // Invalid Pushing the accumulator onto the stack must be coded as PUSH 0E0H ExampleShow 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 = R5Solution:

PUSH 05 ;push R5 onto stackPUSH 0E0H ;push register A onto stackPOP 0F0H ;pop top of stack into B // now register B = register

APOP 02 // pop top of

stack into R2 now R2=R6

Page 166: Embedded system 8051 Microcontroller

4- REGISTER INDIRECT ADDRESSING MODE In register indirect addressing mode, a register is used as a

pointer to the data. If data is inside the CPU, 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 using this addressing mode.

When R0 and R1 are used as pointers , that is, when they hold the address of RAM locations , they must be preceded by the “@” sign. MOV A,@R0 // move contents of RAM location whose address is held by R0

into A. MOV @R1,A // move contents of B into RAM whose address is held by R1

Page 167: Embedded system 8051 Microcontroller

ExampleWrite a program to clear 16 RAM locations starting at RAM address 60HSolution:

CLR A ;A=0MOV R1,#60H ;load pointer. R1=60HMOV R7,#16 ;load counter, R7=16AGAIN: MOV @R1,A ;clear RAM R1 points toINC R1 ;increment R1 pointerDJNZ R7,AGAIN ;loop until counter=zero

Page 168: Embedded system 8051 Microcontroller

5- INDEXED ADDRESSING MODE

Indexed addressing mode is used in accessing data elements of look-up table entries located in program ROM space

Instruction used for this purpose is “@A+DPTR, @A+PC”. The 16-bit register DPTR and register “A” are used to form

the data element stored in on-chip ROM. In this instruction content of A are added to the 16-bit

register DPTR to form the 16-bit address of the needed data.

Page 169: Embedded system 8051 Microcontroller

EXAMPLES

MOVC A,@A+DPTR ; A ROM(A+DPTR) MOVC A,@A+PC ; A ROM(A+PC) JMP @A+DPTR ; PC (A+DPTR)

Page 170: Embedded system 8051 Microcontroller

Example Write a program to copy the value 55H into RAM memory locations 40H to 41H using (a) direct addressing mode(b) register indirect addressing mode without a loop(c) with a loop

Page 171: Embedded system 8051 Microcontroller

Solution:(a) MOV A,#55H //load A with value 55H

MOV 40H,A //copy A to RAM location 40H

MOV 41H.A //copy A to RAM location 41H(b) MOV A,#55H //load A with value 55H

MOV R0,#40H //load the pointer. R0=40HMOV @R0,A //copy A to RAM R0 points

toINC R0 //increment pointer. Now

R0=41hMOV @R0,A //copy A to RAM R0 points to

Page 172: Embedded system 8051 Microcontroller

(c) MOV A,#55H //A=55HMOV R0,#40H //load pointer.R0=40H,

MOV R2,#02 //load counter, R2=3AGAIN: MOV @R0,A //copy 55 to RAM R0 points toINC R0 //increment R0 pointer

DJNZ R2,AGAIN //loop until counter = zero

Page 173: Embedded system 8051 Microcontroller

INSTRUCTION SET OF 8051

Page 174: Embedded system 8051 Microcontroller

ASSEMBLING AND RUNNING AN 8051 PROGRAM

An Assembly language instruction consists of four fields:[label : ] mnemonic [operands] [;comment]

Page 175: Embedded system 8051 Microcontroller

INSTRUCTIONS THAT AFFECT FLAG SETTINGS

Instructions That Affect Flag Bits

Page 176: Embedded system 8051 Microcontroller

INSTRUCTION SET OF 8051

Arithmetic Operation Group Logical Operation Group Data Transfer Group Boolean Variable Manipulation Group Program Branching Group

Page 177: Embedded system 8051 Microcontroller

ARITHMETIC INSTRUCTIONS These instructions are used to perform various

mathematical operations like addition, subtraction, multiplication, and division etc.

Page 178: Embedded system 8051 Microcontroller

ADDITION WITHOUT CARRY ADD A, Source //ADD the source operand to the

accumulator ADD A, R1 // Add the content of register1 to Accumulator ADD A, Direct // ACCACC+ Data of memory location ADD A, #Data Add A, @Ri

Page 179: Embedded system 8051 Microcontroller

ADDITION WITH CARRY► ADDC A,Direct // Add data of memory to accumulator with carry► ADDC A,Rn► ADDC A,@Ri► ADDC A,#2

Page 180: Embedded system 8051 Microcontroller

EXAMPLES MOV A,#25H ;load 25H into A MOV R2,#34H ;load 34H into R2 ADD A,R2 ;add R2 to accumulator

;Executing the program above results in A = 59H

Page 181: Embedded system 8051 Microcontroller

SUBSTRACTION WITH BORROW► SUBB A,Direct► SUBB A,Rn► SUBB A,@Ri► SUBB A,#Data

Page 182: Embedded system 8051 Microcontroller

INCREMENT OPERATION► INC A // Increment accumulator► INC Direct // Increment data at memory

location► INC Rn // Increment data of memory

location► INC @Ri // Increment data at address store

by Ri

Page 183: Embedded system 8051 Microcontroller

DECREMENT OPERATION► DEC A // Decrement accumulator► DEC Direct // Decrement data at memory location► DEC Rn // Decrement data of memory

location► DEC @Ri // Decrement data at address store by

Ri

Page 184: Embedded system 8051 Microcontroller

ARITHMETIC OPERATION GROUP EXAMPLES INC DPTR //Increment DPTR DA A //Decimal adjust

Accumulator(BCD) MUL AB // Multiply A and B DIV AB // Divide A by B

Page 185: Embedded system 8051 Microcontroller

INSTRUCTION SET Arithmetic Operation Group Logical Operation Group Data Transfer Group Boolean Variable Manipulation Group Program Branching Group

Page 186: Embedded system 8051 Microcontroller

LOGICAL OPERATION GROUP The logical instructions are instructions which are used for

performing some operations like AND, OR, NOT, X-OR and etc.

Page 187: Embedded system 8051 Microcontroller

LOGICAL OPERATION-AND► ANL A,Direct► ANL A,Rn► ANL A,@Ri► ANL A,#Data► ANL Direct,A► ANL Direct,#Data

Page 188: Embedded system 8051 Microcontroller

LOGICAL OPERATION-OR ORL A, Direct ORL A, Rn ORL A, @Ri ORL A, #Data ORL Direct, A ORL Direct, #Data

Page 189: Embedded system 8051 Microcontroller

LOGICAL OPERATION-XOR XRL A, Direct XRL A, Rn XRL A, @Ri XRL A, #Data XRL Direct, A XRL Direct, #Data

Page 190: Embedded system 8051 Microcontroller

LOGICAL OPERATION – ROTATE, SWAP RR A // Rotate Accumulator right

If ACC=C3H (11000011), then the instruction results in ACC=E1H (11100001) with the carry unaffected

RRC A //Rotate Accumulator right through carry If ACC=C3H (11000011), and the carry flag is 0, the instruction

results in ACC=61H (01100001) with the carry flag set SWAP A //Swap nibbles with in the Accumulator RL A //Rotate Accumulator left

RLC A //Rotate Accumulator left through carry

Page 191: Embedded system 8051 Microcontroller

LOGICAL OPERATION -CLEAR & CLEAR CLR A //Clear Accumulator CPL A // Complement Accumulator

Page 192: Embedded system 8051 Microcontroller

INSTRUCTION SET Arithmetic Operation Group Logical Operation Group Data Transfer Group Boolean Variable Manipulation Group Program Branching Group

Page 193: Embedded system 8051 Microcontroller

DATA TRANSFER GROUP These instruction are used to transfer the data from source

operand to destination operand. All the store, move, load, exchange input and output

instructions belong to this group.

Page 194: Embedded system 8051 Microcontroller

DATA TRANSFER-MOV

MOV destination, source ;copy source to destination MOV A, Direct MOV A, Rn MOV A, @Ri MOV A, #Data MOV Rn, Direct MOV Rn, @Ri MOV Rn, #Data

Page 195: Embedded system 8051 Microcontroller

DATA TRANSFER-MOV► MOV Direct, Direct► MOV Direct, Rn► MOV Direct, @Ri► MOV Direct, #Data► MOV Direct, A► MOV @Ri, A► MOV @Ri, #Data

Page 196: Embedded system 8051 Microcontroller

DATA TRANSFER-MOV MOV @Ri, Direct MOV DPTR, #DATA16 MOVC A, @A+DPTR MOVC A, @A+PC MOVX A, @Ri MOVX @Ri, A MOVX @DPTR, A

Page 197: Embedded system 8051 Microcontroller

EXAMPLES MOV A,#55H // load value 55H into reg A MOV R0,A //copy contents of A into R0 (A=R0=55H) MOV R1,A //copy contents of A into R1 (A=R0=R1=55H) MOV R2,A //copy contents of A into R2

(A=R0=R1=R2=55H) MOV R3,#95H //load value 95H into R3 (R3=95H) MOV A,R3 //copy contents of R3 into A

(A=R3=95H) MOVX A,@DPTR // Move external RAM to Accumulator

Page 198: Embedded system 8051 Microcontroller

DATA TRANSFER-PUSH,POP PUSH Direct // PUSH direct byte on to stack POP Direct // POP direct byte from stack XCH A,Rn //Exchange ACCUMULATOR with

Register XCH A,Direct // Exchange ACCUMULATOR with data at location XCH A,@Ri XCHD A,@Ri //Exchanges low-order nibble of Accumulator

(bits 3 through 0), with that of internal RAM location indirectly addressed by specified register.High-order nibbles (bits 7-4) of each register are not affected

Page 199: Embedded system 8051 Microcontroller

INSTRUCTION SET Arithmetic Operation Group Logical Operation Group Data Transfer Group Boolean Variable Manipulation Group Program Branching Group

Page 200: Embedded system 8051 Microcontroller

BOOLEAN VARIABLE-SET,CLEAR,COMPLEMENT► CLR C //Clear the carry bit► CLR bit // Clear the bit of any register ► SETBC // Set the carry bit=1► SETB bit //Set the bit of any register► CPL C //Complement the carry► CPL bit //Complement the bit of any register

Page 201: Embedded system 8051 Microcontroller

BIT ADDRESSABLE EXAMPLE

SETB 07Fh ; Bit 7F 1

SETB 2F.7 ; same

Page 202: Embedded system 8051 Microcontroller

BOOLEAN VARIABLE-AND,OR,MOV► ANL C,bit► ANL C,/bit ► ORL C,bit► ORL C,/bit► MOV C,bit► MOV bit,C

Page 203: Embedded system 8051 Microcontroller

INSTRUCTION SET► Arithmetic Operation Group► Logical Operation Group ► Data Transfer Group► Boolean Variable Manipulation Group► Program Branching Group

Page 204: Embedded system 8051 Microcontroller

These instructions are used for jump, call instruction as well as branch instruction. Program flow change in branch instruction if condition met Program flow always change in jump and call instruction

Page 205: Embedded system 8051 Microcontroller

CONDITIONAL JUMP INSTRUCTIONS JC // Jump if carry equal to one JNC // Jump if carry equal to zero JB // Jump if bit equal to one JNB // Jump if bit equal to zero JBC // Jump if bit equal to one and clear bit JZ // Jump if A=Zero JNZ // Jump if A not equal to zero DJNZ// Decrement and Jump if not equal to zero. CJNE A, P1,rel //compare and jump if not equal

Page 206: Embedded system 8051 Microcontroller

CJNE A,Direct,rel //Compare and Jump if Not Equal CJNE A,#Data,rel CJNE Rn,#Data,rel CJNE @Ri,#Data,rel DJNZ Rn,rel //Decrement and jump if not zero DJNZ Direct,relEXAMPLE The Accumulator contains 34H. Register 7 contains 56H. The

first instruction in the sequence,CJNE R7, # 60H, NOT_EQ ; . . . . . . . . ;R7 = 60H.NOT_EQ: JC REQ_LOW ;IF R7 < 60H.. . . . . . . . …………………;R7 > 60H.

Page 207: Embedded system 8051 Microcontroller

► Unconditional Jump Instructions The unconditional jump is a jump in which

control is transferred unconditionally to the target location

► In 8051 there two unconditional jumps. They are:► SJMP addr16 // Short jump► LJMP rel // Long jump

Page 208: Embedded system 8051 Microcontroller

LJMP ADDR16

LJMP causes an unconditional branch to the indicated address, by loading the high-order and low-order bytes of the PC (respectively) with the second and third instruction bytes. The destination may therefore be anywhere in the full 64K program memory address space. No flags are affected.

LJMP (PC) ← addr15-0

Page 209: Embedded system 8051 Microcontroller

LCALL ADDR16 LCALL calls a subroutine located at indicated address. Instruction adds three to program counter to generate address

of next instruction and then pushes the 16-bit result onto stack (low byte first), incrementing the Stack Pointer by two.

High-order and low-order bytes of the PC are then loaded, respectively, with second and third bytes of LCALL instruction.

Program execution continues with instruction at this address. The subroutine may therefore begin anywhere in the full 64K byte program memory address space. No flags are affected.

Page 210: Embedded system 8051 Microcontroller

LCALL OPERATIONLCALL(PC) ← (PC) + 3(SP) ← (SP) + 1((SP)) ← (PC7-0)(SP) ← (SP) + 1((SP)) ← (PC15-8)(PC) ← addr15-0

Page 211: Embedded system 8051 Microcontroller

PROGRAM BRANCHING GROUP► NOP

► Execution continues at the following instruction. Operation

(PC) ← (PC) + 1

Page 212: Embedded system 8051 Microcontroller

ACALL ADDR11 ACALL unconditionally calls a subroutine located at the

indicated address. The instruction increments the PC twice to obtain the

address of the following instruction, then pushes the 16-bit result onto the stack (low-order byte first) and increments the Stack Pointer twice.

The destination address is obtained by successively concatenating the five high-order bits of the incremented PC, opcode bits 7 through 5, and the second byte of the instruction.

The subroutine called must therefore start within the same 2 K block of the program memory as the first byte of the instruction following ACALL. No flags are affected.

Page 213: Embedded system 8051 Microcontroller

2-byte instructions where the 11-bit absolute address is specified as the operand

Upper 5 bits of 16-bit PC address are not modified. The lower 11 bits are loaded from this instruction. So, the branch address must be within the current 2K byte page of program memory (211 = 2048)

Example:ACALL PORT_INIT ;PORT_INIT should be located within 2k bytes.

PORT_INIT: MOV P0, #0FH ;PORT_INIT subroutine

Page 214: Embedded system 8051 Microcontroller

The label JMPADR is at program memory location 0123H. The following instruction,AJMP JMPADR

is at location 0345H and loads the PC with 0123H.a10 a9 a8 0 0 0 0 1 a7 a6 a5 a4 a3 a2 a1 a0Operation: AJMP(PC) ← (PC) + 2(PC10-0) ← page address

Page 215: Embedded system 8051 Microcontroller

ASSEMBLER DIRECTIVE-DB DB directive is most widely used data directive in the assembler It is used to define the 8-bit data DB is used to define data in decimal, binary, hex,ASCII formats

ORG 500H DATA1: DB 28 ;DECIMAL (1C in Hex) DATA2: DB 00110101B ;BINARY (35 in Hex) DATA3: DB 39H ;HEX ORG 510H DATA4: DB “2591” ;ASCII NUMBERS ORG 518H DATA6: DB “My name is Joe” ;ASCII CHARACTERS

Page 216: Embedded system 8051 Microcontroller

ORG (ORIGIN) The ORG directive is used to indicate beginning of the

address Number that comes after ORG can be either in hex and

decimal If the number is not followed by H, it is decimal & assembler

will convert it to hex

Page 217: Embedded system 8051 Microcontroller

END This indicates to the assembler the end of source (asm) file The END directive is last line of an 8051 program It’s mean that in the code anything after the END directive

is ignored by the assembler

Page 218: Embedded system 8051 Microcontroller

EQU (EQUATE) Used to define a constant without occupying memory

location EQU directive does not set aside storage for a data item

but associates a constant value with a data label When label appears in program, its constant value will be

substituted for label Assume that there is a constant used in many different

places in program, & programmer wants to change its value throughout

Page 219: Embedded system 8051 Microcontroller

By the use of EQU, one can change it once and the assembler will change all of its occurrences COUNT EQU 25 ... .... MOV R3, #COUNT

Page 220: Embedded system 8051 Microcontroller

STRUCTURE OF ASSEMBLY LANGUAGE ORG 0H // start (origin) at 0 MOV R5,#25H // load 25H into R5 MOV R7,#34H // load 34H into R7 MOV A,#0 // load 0 into A ADD A,R5 // add contents of R5 to A now A = A

+ R5 ADD A,R7 // add contents of R7 to A now A = A

+ R7 ADD A, #12H // add to A value 12H now A = A +

12H HERE: SJMP HERE // stay in this loop END // end of asm source file

Page 221: Embedded system 8051 Microcontroller

EMBEDDED C

Page 222: Embedded system 8051 Microcontroller

Whenever the conventional ‘C’ language and its extensions are used for programming embedded system, it is referred to as Embedded C programming

Page 223: Embedded system 8051 Microcontroller

WHY PROGRAM 8051 IN C 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

Page 224: Embedded system 8051 Microcontroller

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

Page 225: Embedded system 8051 Microcontroller

UNSIGNED CHAR The character data type is the most natural choice

8051 is an 8-bit microcontroller Unsigned char is 8-bit data type in range of 0 – 255 (00 –

FFH) One of most widely used data types for the 8051

Counter value ASCII characters

C compilers use the signed char as the default if we do not put the keyword unsigned

Page 226: Embedded system 8051 Microcontroller

UNSIGNED CHAR (CONT’) Write an 8051 C program to send values 00 – FF

to port P1.

#include <reg51.h> void main(void) { unsigned char z; for (z=0;z<=255;z++) P1=z; }

Page 227: Embedded system 8051 Microcontroller

DATA TYPES- UNSIGNED CHAR (CONT’) Write an 8051 C program to send hex values for ASCII

characters of 0, 1, 2, 3, 4, 5, A, B, C, and D to port P1. #include <reg51.h> void main(void) { unsigned char mynum[]=“012345ABCD”; unsigned char z; for (z=0;z<=10;z++) P1=mynum[z]; }

Page 228: Embedded system 8051 Microcontroller

UNSIGNED CHAR (CONT’) Write an 8051 C program to toggle all the bits of P1

continuously.#include <reg51.h>void main(void){for (;;){p1=0x55;p1=0xAA;}

}

Page 229: Embedded system 8051 Microcontroller

SIGNED CHAR The signed char is an 8-bit data type

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

Page 230: Embedded system 8051 Microcontroller

SIGNED CHAR (CONT’) Write an 8051 C program to send values of –4 to +4 to port

P1.#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];}

Page 231: Embedded system 8051 Microcontroller

UNSIGNED AND SIGNED INT 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

Page 232: Embedded system 8051 Microcontroller

SINGLE BIT Write an 8051 C program to toggle bit D0 of the port P1 (P1.0) 50,000 times. #include <reg51.h> sbit MYBIT=P1^0; void main(void) { unsigned int z; for (z=0;z<=50000;z++) { MYBIT=0; MYBIT=1; } }

Page 233: Embedded system 8051 Microcontroller

BIT AND SFR The bit data type allows access to single bits of bit-

addressable memory spaces 20 – 2FH To access the byte-size SFR registers, we use the sfr data

type 7FH

30H

2FH

20H1FH

17H10H0FH

07H08H

18H

00HRegister Bank 0

(Stack )Register Bank 1

Register Bank 2

Register Bank 3

Bit-Addressable RAM

Scratch pad RAM

Page 234: Embedded system 8051 Microcontroller

DELAY IN 8051

Page 235: Embedded system 8051 Microcontroller

TIME DELAY There are two way s to create a time delay in 8051 C

Using the 8051 timer 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

Page 236: Embedded system 8051 Microcontroller

Write an 8051 C program to toggle bits of P1 continuously forever with some delay.

//Toggle P1 forever with some delay in between “on” and “off” #include <reg51.h> void main(void) { 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++); }}

Page 237: Embedded system 8051 Microcontroller

#include <reg51.h>void MSDelay(unsigned int);void main(void){

while (1) //repeat forever{ p1=0x55;MSDelay(250);p1=0xAA;MSDelay(250); }

}

void MSDelay(unsigned int itime)

{unsigned int i,j;for (i=0;i<itime;i++)for (j=0;j<1275;j++);

}

Write 8051 program to toggle bits of P1 ports continuously with 250 ms.

Page 238: Embedded system 8051 Microcontroller

LEDs are connected to bits P1 and P2. Write an 8051 C program that shows the count from 0 to FFH (0000 0000 to 1111 1111 in binary) on the LEDs.

#include <reg51.h>#define LED P2void main(void){P1=00; //clear P1LED=0; //clear P2for (;;) //repeat forever{P1++; //increment P1LED++; //increment P2}}

Page 239: Embedded system 8051 Microcontroller

Write an 8051 C program to monitor bit P1.5. If it is high, send 55H to P0; otherwise, send AAH to P2.

#include <reg51.h> sbit mybit=P1^5; void main(void) { mybit=1; //make mybit an input while (1) { if (mybit==1) P0=0x55; else P2=0xAA; }}

Page 240: Embedded system 8051 Microcontroller

Write an 8051 C program to read the P1.0 and P1.1 bits and issue an ASCII character to P0 according to the following table.

P1.1 P1.00 0 send ‘0’ to P00 1 send ‘1’ to P01 0 send ‘2’ to P01 1 send ‘3’ to P0

Page 241: Embedded system 8051 Microcontroller

#include <reg51.h> void main(void) { unsigned char z; z=P1; z=z&0x3; switch (z) { case(0): { P0=‘0’; break; }

case(1):{P0=‘1’;break;}case(2):{P0=‘2’;break;}case(3):{P0=‘3’;break;}}}

Page 242: Embedded system 8051 Microcontroller

PROTEUS

Page 243: Embedded system 8051 Microcontroller

After perfecting your project on programming side in KEIL, you'll need to simulate it on PROTEUS to determine output of hardware components and change it if need be.

This will completely ensure your project's success.

Page 244: Embedded system 8051 Microcontroller

Place your components from library Connect them accordingly Load HEX file (if 8051 is involved) Simulate the circuit

Page 245: Embedded system 8051 Microcontroller

PLACING COMPONENTS

Click "Pick from library (P)" button as shown in figure

Select any category Select item from the list Click OK

Page 246: Embedded system 8051 Microcontroller

After selecting component, click anywhere in design area to select it and then click again to place it

Page 247: Embedded system 8051 Microcontroller

CONNECTING COMPONENTS Place all the required components Connect desired nodes by clicking at starting &ending

points

Page 248: Embedded system 8051 Microcontroller

LOAD HEX FILE Double click the 8051 component to open its properties Browse for the HEX file as shown and select it

Page 249: Embedded system 8051 Microcontroller

SIMULATING THE CIRCUIT

Controls at left-bottom corner will help you simulate circuit in real time

Page 250: Embedded system 8051 Microcontroller

BLINKING OF LED

Page 251: Embedded system 8051 Microcontroller

#include<reg51.h> sbit LED = P1^0; // Pin P1.0 is named as

LED void x(void); //Function declarations void delay(int a); //Function declarations int main(void) { x(); // Make all ports as output port while(1) { LED = 0; // Pin P1.0 Low delay(30000); // Half sec delay LED = 1; // Pin P1.0 High delay(30000); // Half sec delay }}

void delay(int a){ int i; for(i=0;i<a;i++); //null statement}

void x(void){P0 = 0x00; P1 = 0x00; P2 = 0x00; P3 = 0x00; }

Page 252: Embedded system 8051 Microcontroller
Page 253: Embedded system 8051 Microcontroller

INTERFACING LCD TO 8051

LCD is finding widespread use replacing LEDs The declining prices of LCD The ability to display numbers, characters, and graphics Ease of programming for characters and graphics

Page 254: Embedded system 8051 Microcontroller

Pin Symbol I/O Description1 VSS -- Ground2 VCC -- +5V power supply3 VEE -- Power supply to control contrast4 RS(Register

select)I RS=0 to select command register,

RS=1 to select data register5 R/W I R/W=0 for write,

R/W=1 for read6 E I Enable7 DB0 I/O The 8-bit data bus8 DB1 I/O The 8-bit data bus9 DB2 I/O The 8-bit data bus10 DB3 I/O The 8-bit data bus11 DB4 I/O The 8-bit data bus12 DB5 I/O The 8-bit data bus13 DB6 I/O The 8-bit data bus14 DB7 I/O The 8-bit data bus15 BL+ -- Brightness16 BL- -- Ground

Page 255: Embedded system 8051 Microcontroller

RESISTER SELECT(RS) PIN

Control Register Used for instructing LCD on what

to do next. It's like talking to your LCD using this register.

Data Register Used for displaying data on

LCD. 

Page 256: Embedded system 8051 Microcontroller

No. Instruction Hex Decimal1 Function Set: 8-bit, 1 Line, 5x7 Dots 0x30 482 Function Set: 8-bit, 2 Line, 5x7 Dots 0x38 565 Entry Mode 0x06 6

6 Display off Cursor off(clearing display without clearing DDRAM content) 0x08 8

7 Display on Cursor on 0x0E 148 Display on Cursor off 0x0C 129 Display on Cursor blinking 0x0F 1510 Shift entire display left 0x18 2411 Shift entire display right 0x1C 3012 Move cursor left by one character 0x10 1613 Move cursor right by one character 0x14 2014 Clear Display (also clear DDRAM content) 0x01 1

Page 257: Embedded system 8051 Microcontroller

R/W (READ/WRITE) CONTROL PIN Determine the flow of data.

Write Mode when you're sending something to LCD (data or command)

Read Mode when you're reading from the LCD

Page 258: Embedded system 8051 Microcontroller

 It is basically called 16x2 LCD Sixteen columns & two rows thus it can display thirty-

two (32) characters at a time (sixteen characters in each row)

Connect potentiometers to Vee or BL controls to control the contrast or Brightness yourself.

Page 259: Embedded system 8051 Microcontroller

LCD PROGRAM CODE IN A STEPWISE FASHION

Page 260: Embedded system 8051 Microcontroller

1- Unique name to each pin on LCD using #define directive so that you can mention them easily

Page 261: Embedded system 8051 Microcontroller

To differentiate between command and data as discussed above, create two separate functions. As you can see, the only difference is that of using RS pin according to requirement.

Page 262: Embedded system 8051 Microcontroller

The delay function is general one and you can use it safely.

Page 263: Embedded system 8051 Microcontroller

main function

Page 264: Embedded system 8051 Microcontroller

To send a command to LCD, use the lcdcmd function with command as input.

To send data to LCD, use the lcddata function with the data as input.

 LCD accepts only ASCII characters which means that every character you send for display must be in ASCII

Page 265: Embedded system 8051 Microcontroller

x = 'A'lcddata ( x )

x = 65     //decimal valuelcddata ( x )

x = 0x41 //hexadecimal valuelcddata ( x )

lcddata ( 'A' ) where x can be of type char or int whether signed or unsigned. 

Page 266: Embedded system 8051 Microcontroller

KEIL-LCD INTERFACING#include <REGX51.H> //header file

#define lcdport P2 //port 2 of microcontroller#define rs P3_0 //port 3 pin 0 of microcontroller#define rw P3_1 //port 3 pin 1 of microcontroller#define e P3_2 //port 3 pin 2 of microcontroller

void lcdcmd (unsigned char); //function define for lcd command modevoid lcddata(unsigned char); //function define for lcd data modevoid delay (unsigned int); //function define for delay mode

Page 267: Embedded system 8051 Microcontroller

void main(){

//INITIALIZE LCDlcdcmd(0x38); //for using 8-bit double row mode of LCDlcdcmd(0x0E); //turn display ON for cursor blinkinglcdcmd(0x01); //clear screen//PRINT A CHARACTERlcddata(‘E');lcddata(‘F');lcddata('A');while(1);

}//*********Function to send command to LCD*******//void lcdcmd(unsigned char value) {

lcdport = value;rw = 0; // write moders = 0; //register select command registere=1; //enable chipdelay(1); //delaye=0; // disable chip

}

Page 268: Embedded system 8051 Microcontroller

//**********Function to send data to LCD**********//void lcddata(unsigned char value) {

lcdport = value;rw = 0; // write moders = 1; //register select data mode

e=1; //enable lcddelay(1);e=0; //disable lcd

}

void delay(unsigned int msec) // Function to provide time delay in msec.{

int i,j ;for(i=0;i<msec;i++)for(j=0;j<1275;j++);

}

Page 269: Embedded system 8051 Microcontroller

PROTEUS- LCD INTERFACING SCHEMATIC

Page 270: Embedded system 8051 Microcontroller

STEPPER MOTOR INTERFACING

Page 271: Embedded system 8051 Microcontroller

A Stepper Motor is a brushless, synchronous DC Motor. Performs many applications in field of robotics. The total rotation of motor is divided into steps. Angle of a single step is known as stepper angle of motor. There are two types of stepper motors Unipolar and

Bipolar. Due to the ease of operation unipolar stepper motor is

commonly used by electronics hobbyists. Stepper Motors can be easily interfaced with a

microcontroller using driver ICs such as L293D or ULN2003.

Page 272: Embedded system 8051 Microcontroller

WORKING OF STEPPER MOTOR Stepper motors works on the principle of electromagnetic induction. Ordinary DC Brush motors rotate continuously when DC voltage is

applied to their terminals. While stepper motor need a sequence of digital pulses for one complete

rotation. Stepper motor contains a magnetic or soft iron rotor surrounded by

electromagnetic stators. Stator and rotor have poles which may be teethed depending on type of

stepper motor. Firstly one stator electromagnet is energised, this makes rotor teeth

magnetically attracted to electromagnet’s teeth. When rotor teeth gets align with first electromagnet, it gets misaligns

with next electromagnet. So when next electromagnet is turned on and first one is turned off, rotor rotates to align with next one. This process is repeated to get required rotation.

Page 273: Embedded system 8051 Microcontroller

TYPES OF STEPPER MOTOR

Stepper Motors are classified in to three types depending upon its construction.

Permanent Magnet Stepper Variable Reluctance  Stepper Hybrid Stepper

Page 274: Embedded system 8051 Microcontroller

PERMANENT MAGNET STEPPER It has a permanent magnet in rotor and operates on repulsion

and attraction between permanent magnet rotor and stator electromagnets.

Stator and rotor poles of these types are not teethed.  First a stator is energized, it develops electromagnetic north and south poles. It rotates rotor to align with magnetic field of stator.

Then other stators are energised in sequentially this rotates rotor to align with new magnetic field.

Through this way we can rotate rotor through fixed steps.

Page 275: Embedded system 8051 Microcontroller

VARIABLE RELUCTANCE STEPPER These types of motors operates on principle that minimum

reluctance occurs with minimum gap and it has a non-magnetic toothed soft iron rotor.

When a stator is energised, rotor rotates to have a minimum gap between the stator and its teeth.

The rotor teeth is designed such that when it aligns with one stator, they will get misaligned with then next stator.

Thus by energising stators sequentially we can rotate the rotor.

Page 276: Embedded system 8051 Microcontroller

HYBRID STEPPER These types of motors are a combination of Permanent

Magnet and Variable Reluctance techniques to achieve maximum power in a small package size.

It has a teethed magnetic rotor which can better guides magnetic flux to preferred location in the air gap.

Usually electromagnets of stepper motor is energised using special controlling circuits, such as microcontrollers.

Page 277: Embedded system 8051 Microcontroller

Stepper Motors are classified into two, based on its winding arrangement. Unipolar Motors Bipolar Motors

Page 278: Embedded system 8051 Microcontroller

UNIPOLAR MOTORS A unipolar motor contains centre tapped  windings. Usually centre connection of coils are tied together and used as

power connection. By using this arrangement a magnetic poles can be reversed

without reversing direction of current. Thus the commutation circuit can be made very simple. This ease of operation makes Unipolar Motor popular among

electronics hobbyists.

Page 279: Embedded system 8051 Microcontroller

BIPOLAR MOTORS Bipolar motors have no center tap connections. Current through winding should be reversed to reverse

magnetic poles. So driving circuit is complicated. We can solve this by using a H-bridge connection or by using

ready made chips such as L293D. We can distinguish bipolar motors from unipolar motors by

measuring coil resistance. In bipolar motors we can find two wires with equal

 resistance.

Page 280: Embedded system 8051 Microcontroller

DRIVING OF STEPPER MOTOR – STEPPING MODES

Stepping Modes refers to sequence in which stator electromagnets are energised to rotate stepper motor.

There are three types of stepping modes.

Page 281: Embedded system 8051 Microcontroller

WAVE DRIVE – ONE ON AT A TIME Only one stator electromagnet is energised at a time. It has same number of steps as full step drive but torque is

significantly less. It is rarely used.

Page 282: Embedded system 8051 Microcontroller

FULL DRIVE – TWO ON AT A TIME Two stator electromagnets are energised at a time. It is the usual method used for driving and the motor will

run at its full torque in this mode of driving.

Page 283: Embedded system 8051 Microcontroller

HALF DRIVE – ONE OR TWO ON AT A TIME

Alternatively one and two phases are energised. This mode is commonly used to increase angular

resolution of motor but the torque is less approximately 70% at its half step position (when only a single phase is on)

Page 284: Embedded system 8051 Microcontroller

DRIVING UNIPOLAR STEPPER MOTOR WITH 8051

Unipolar stepper motors can be used in three modes namely Wave Drive, Full Drive and Half Drive mode.

Each drive have its own advantages and disadvantages, thus we should choose required drive according to application and power consumption.

Page 285: Embedded system 8051 Microcontroller

WAVE DRIVE One electromagnet is energized at a time. Generated torque

will be less when compared to full drive in which two electromagnets are energized at a time but power consumption is reduced.

It has same number of steps as in the full drive. This drive is preferred when power consumption is more important than torque.

It is rarely used.

Page 286: Embedded system 8051 Microcontroller

FULL DRIVE Two electromagnets are energized at a time, so the torque

generated will be larger when compared to Wave Drive. This drive is commonly used than others. Power

consumption will be higher than other modes.

Page 287: Embedded system 8051 Microcontroller

HALF DRIVE Alternatively one and two electromagnets are energized, so

it is a combination of Wave and Full drives. This mode is commonly used to increase angular

resolution of motor but the torque will be less, about 70% at its half step position. We can see that the angular resolution doubles when using Half Drive.

Page 288: Embedded system 8051 Microcontroller

INTERFACING USING L293D Driving a bipolar stepper motor using 8051 microcontroller using L293D.

24MHz crystal is connected to provide required clock for microcontroller.

10μF capacitor and 10KΩ is used to provide Power On Reset (POR) for 8051 microcontroller.

L293D is connected to pins P2.0, P2.1, P2.2, P2.3 of the microcontroller and two pairs of L293D are enabled by tieing EN1, EN2 to 5V.

Logic Voltage (5V) is connected to Vss pin and Motor Supply (12V) is connected to the Vs pin of L293D. 

Center Tap of each windings of stepper motor is shorted and connected to the motor supply.

Now we can energize each winding of the motor by making corresponding pin of L293D LOW.

Page 289: Embedded system 8051 Microcontroller

INTERFACING BIPOLAR STEPPER MOTOR WITH 8051 USING L293D

Page 290: Embedded system 8051 Microcontroller

INTERFACING UNIPOLAR STEPPER MOTOR WITH 8051USING L293D

Page 291: Embedded system 8051 Microcontroller

INTERFACING UNIPOLAR STEPPER MOTOR WITH 8051 USING ULN2003

Page 292: Embedded system 8051 Microcontroller

KEIL - C CODE FOR WAVE DRIVE#include<reg51.h>void delay(int);void main(){

do { P2=0x01; //0001 delay(1000); P2=0x02; //0010 delay(1000); P2=0x04; //0100

delay(1000); P2=0x08; //1000 delay(1000); }while(1);}

void delay( int k) //Delay function{ int i,j;

for(i=0;i<k;i++) { for(j=0;j<100;j++) {} }

}

Page 293: Embedded system 8051 Microcontroller

KEIL - C CODE FOR FULL DRIVE#include<reg51.h>void delay(int);void main(){

do { P2 = 0x03; //0011 delay(1000); P2 = 0x06; //0110 delay(1000); P2 = 0x0C; //1100 delay(1000);

P2 = 0x09; //1001 delay(1000); }while(1);}

void delay(int k) //Delay function{ int i,j; for(i=0;i<k;i++) { for(j=0;j<100;j++) {} }}

Page 294: Embedded system 8051 Microcontroller

KEIL - C CODE FOR HALF DRIVE#include<reg51.h>void delay(int);void main(){ do { P2=0x01; //0001 delay(1000);

P2=0x03; //0011 delay(1000);

P2=0x02; //0010 delay(1000);

P2=0x06; //0110 delay(1000);

P2=0x04; //0100 delay(1000);

P2=0x0C; //1100 delay(1000);

P2=0x08; //1000 delay(1000);

P2=0x09; //1001 delay(1000);

} while(1);}

void delay(int k) //Delay Function{ int i,j; for(i=0;i<k;i++) { for(j=0;j<100;j++) {} }}

Page 295: Embedded system 8051 Microcontroller

INTERFACING BIPOLAR STEPPER MOTOR Bipolar stepper motors have no center tap and having

equal coil resistances. It can be easily interfaced with a microcontroller using

L293D DC Motor Driver IC.

Page 296: Embedded system 8051 Microcontroller

KEIL-CODE FOR BIPOLAR STEPPER MOTOR#include<reg51.h>void delay(int);void main(){ do { P2=0x01; //0001 delay(1000); P2=0x04; //0100 delay(1000); P2=0x02; //0010 delay(1000);

P2=0x08; //1000 delay(1000); }while(1);}

void delay(int k) //Delay function{ int i,j; for(i=0;i<k;i++) { for(j=0;j<100;j++) {} }}

Page 297: Embedded system 8051 Microcontroller

PROTEUS –MOTOR INTERFACING

Page 298: Embedded system 8051 Microcontroller

SEVEN SEGMENT DISPLAY INTERFACING

Page 299: Embedded system 8051 Microcontroller

Seven Segment Display which is most commonly known as SSD is an output device which can be used to display information.

SSDs are also composed of individual LEDs and work on the very same principle. So basically they come in two forms

Common Anode Common Cathode

Page 300: Embedded system 8051 Microcontroller

FOR COMMON CATHODE Connect INPUT VOLTAGE to A Connect GROUND to COMMON 

FOR COMMON ANODE Connect INPUT VOLTAGE to COMMON Connect GROUND to A

Page 301: Embedded system 8051 Microcontroller

PIN DESCRIPTION OF STANDARD SSD

Page 302: Embedded system 8051 Microcontroller

SEVEN SEGMENT INTERFACING #include <reg51.H> #define input P1 #define output P2 unsigned char ssd[16] = { 0x7E, 0x30, 0x6D, 0x79, 0x33, 0x5B, 0x5F,0x70,0x7F,

0x7B, 0x77, 0x1F, 0x4E, 0x3D, 0x4F, 0x47 };

void main() { //declare PORT1 as INPUT input = 0xFF; while(1) output = ssd[ input ]; }

Page 303: Embedded system 8051 Microcontroller

PROTEUS - SSD INTERFACE

Page 304: Embedded system 8051 Microcontroller

SWITCH

Page 305: Embedded system 8051 Microcontroller

KEIL -SWITCH INTERFACE#include <reg51.h>#define button P1_0#define led P1_1

void main(){ button = 1;

led = 0;while(1){

if(!button)led = 1;

elseled = 0; }}

Page 306: Embedded system 8051 Microcontroller

PROTEUS-SWITCH INTERFACE WITH 8051

Page 307: Embedded system 8051 Microcontroller