UNIT 5 MP&MC (Final)
UNIT 5 MP&MC (Final)
The 8 bits of a register are shown from MSB D7 to the LSB D0 With an 8-bit data type, any data larger
than 8 bits must be broken into 8-bit chunks before it is processed.
The 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).
Important Terms
Label:. The label is a symbolic address for the instruction. When the program is assembled, the label will
be given specific address in which that instruction is stored. Unless that specific line of instruction is
needed by a branching instruction in the program, it is not necessary to label that line.
Opcode: Opcode is the symbolic representation of the operation. The assembler converts the opcode
to a unique binary code (machine language).
Operand: While opcode specifies what operation to perform, operand specifies where to perform that
action. The operand field generally contains the source and destination of the data. In somecases only
source or destination will be available instead of both. The operand will be either address of the data,
or data itself.
Comment:-Always comment will begin with ;or // symbol. To improve the program quality,
programmer may always use comments in the program.
In the early days of the computer, programmers coded in machine language, consisting of 0 s and
1s which is Tedious, slow and prone to error. Assembly languages, which provided mnemonics for the
machine code instructions, plus other features, were developed. An Assembly language program consist
of a series of lines of Assembly language instructions .Assembly language is referred to as a low level
language It deals directly with the internal structure of the CPU.
3) Assembler require a third step called linking .The linker program takes one or more object code files
and produce an absolute object file with the extension “abs” .This abs file is used by 8051 trainers that
have a monitor program.
4) Next the “abs” file is fed into a program called “OH” (object to hex converter) which creates a file
with extension “hex” that is ready to burn into ROM. This program comes with all 8051 assemblers.
Recent Windows-based assemblers combine step 2 through 4 into one step.
Following figure shows the steps required in programming:-
Fig 1 – Step for programming
Lst file:- The lst (list) file, which is optional, is very useful to the programmer .It lists all the opcodes and
addresses as well as errors that the assembler detected. The programmer uses the lst file to find the syntax
errors or debug.
Program Counter:- The program counter points to the address of the next instruction to be executed .As
the CPU fetches the opcode from the program ROM, the program counter is increasing to point to the
next instruction ‰ The program counter is 16 bits wide . This means that it can access program addresses
0000 to FFFFH, a total of 64K bytes of code.
Power up:- All 8051 members start at memory address 0000 when they’re powered up . Program
Counter has the value of 0000 .The first opcode is burned into ROM address 0000H, since this is where
the 8051 looks for the first instruction when it is booted. We achieve this by the ORG statement in the
source program.
Executing Program
Consider following example. A step-by-step description of the action of the 8051 upon applying power
on it:-
1. When 8051 is powered up, the PC has 0000 and starts to fetch the first opcode from
location 0000 of program ROM. Upon executing the opcode 7D, the CPU fetches the
value 25 and places it in R5. Now one instruction is finished, and then the PC is
incremented to point to 0002, containing opcode 7F 2. Upon executing the opcode 7F, the
value 34H is moved into R7 . The PC is incremented to 0004.
2. Upon executing the opcode 7F, the value 34H is moved into R7 .The PC is incremented to
0004
3. The instruction at location 0004 is executed and now PC = 0006
4. After the execution of the 1-byte instruction at location 0006, PC = 0007
5. Upon execution of this 1-byte instruction at 0007, PC is incremented to 0008.
This process goes on until all the instructions are fetched and executed. The fact that program counter
points at the next instruction to be executed explains some microprocessors call it the instruction pointer.
EQU and SET directives assign numerical value or register name to the specified symbol name. EQU
is used to define a constant without storing information in the memory. The symbol defined with
EQU should not be redefined. SET directive allows redefinition of symbols at a later stage.
DB (Define Byte):-
The DB directive is used to define an 8 bit data. DB directive initializes memory with 8 bit values. The
numbers can be in decimal, binary, hex or in ASCII formats. For decimal, the 'D' after the decimal
number is optional, but for binary and hexadecimal, 'B' and ‘H’ are required. For ASCII, the number is
written in quotation marks (‘LIKE This).
Explanation:-
1. Data transfer instructions
In this group, the instructions perform data transfer operations of the following types.
In this group, the instructions perform data transfer operations of the following types.
a. Move the contents of a register Rn toA
i. MOVA,R2
ii. MOVA,R7
b. Move the contents of a register A toRn
i. MOVR4,A
ii. MOVR1,A
c. Move an immediate 8 bit data to register A or to Rn or to a memory location(direct
or indirect)
i. MOV A,#45H MOV @R0, #0E8H
ii. MOV R6,#51H iv. MOV DPTR,#0F5A2H
iii. MOV 30H,#44H v. MOV DPTR,#5467H
d. Move the contents of a memory location to A or A to a memory location using direct
and indirect addressing
i. MOV A,65H
ii. MOV A,@R0
iii. MOV 45H,A
iv. MOV @R1,A
e. Move the contents of a memory location to Rn or Rn to a memory location using
direct addressing
i. MOV R3,65H
ii. MOV 45H,R2
f. Move the contents of memory location to another memory location using direct
and indirect addressing
i. MOV 47H,65H
ii. MOV 45H,@R0
g. Move the contents of an external memory to A or A to an external memory
i. MOVXA,@R1
ii. MOVX@R0,A
h. Move the contents of program memory to A
1. MOVC A,@A+PC
2. MOVC A,@A+DPTR
3. MOVXA,@DPTR
4. MOVX@DPTR,A
Exchange Instructions
The content of source ie., register, direct memory or indirect memory will be
exchanged with the contents of destination ie., accumulator.
i. XCHA,R3
ii. XCHA,@R1
iii. XCHA,54h
j. Exchange digit. Exchange the lower order nibble of Accumulator (A0-A3) with lower order
nibble of the internal RAM location which is indirectly addressed by theregister.
i. XCHDA,@R1
ii. XCHDA,@R0
2.Arithmetic Instructions:-
The 8051 can perform addition, subtraction. Multiplication and division operations on 8 bit
numbers.
Addition
Subtraction
Multiplication
MUL AB. This instruction multiplies two 8 bit unsigned numbers which are stored in A and B
register. After multiplication the lower byte of the result will be stored in accumulator and higher byte
of result will be stored in B register.
Eg. MOV A,#45H ;[A]=45H
MOV B, #0F5H
;[B]=F5H
MUL AB ;[A]x[B]=45xF5=4209
;[A]=09H, [B]=42H
Division:-
DIV AB. This instruction divides the 8 bit unsigned number which is stored in A by the 8 bit unsigned
number which is stored in B register. After division the result will be stored in accumulator and
remainder will be stored in B register.
Eg. MOVA, #45H ;[A]=0E8H
MOV B,#0F5H ;[B]=1BH
DIVAB ;[A]/[B]=E8/1B=08Hwithremainder10H
When two BCD numbers are added, the answer is a non-BCD number. To get the result in BCD, we
use DA A instruction after the addition. DA A works as follows.
MOV R1,#55H
ADDA,R1 //[A]=78
DA A // [A]=78 no changes in the accumulator after DAA.
MOV R1,#58H
ADDA,R1 //[A]=ABh
DA A //[A]=11,C=1.ANSWERIS111.AccumulatordataischangedafterDAA
Increment:
INC A
INC Rn
INC DIRECT
INC @RiINCDPTR
INC increments the value of source by1. If the initial value of register is FFH, incrementing the value
will cause it to reset to 0. The Carry Flag is not set when the value "rolls over" from 255 to 0.In the
case of "INC DPTR", the value two-byte unsigned integer value of DPTR is incremented. If the initial
value of DPTR is FFFFh, incrementing the value will cause it to reset to 0.
Decrement:
Decrements the operand by one.
DEC A
DEC Rn
DEC DIRECT
DEC@Ri
DEC decrements the value of source by 1. If the initial value of is 0, decrementing the value will cause
it to reset to FFh. The Carry Flag is not set when the value "rolls over" from 0 to FFh.
Logical Instructions
ANL destination, source:
ANL does a bitwise "AND" operation between source and destination, leaving the resulting value in
destination. The value in source is not affected. "AND" instruction logically AND the bits of source
and destination.
ANL A,#DATA
ANL A, Rn
ANL A,DIRECT
ANL A,@Ri
ANL DIRECT,A
ANL DIRECT, #DATA
Logical OR
ORL destination, source:
ORL does a bitwise "OR" operation between source and destination, leaving the resulting value in
destination. The value in source is not affected. " OR " instruction logically OR the bits of source and
destination.
ORLA,#DATA
ORL A, Rn
ORL A,DIRECT
ORL A,@Ri
ORL DIRECT,A
ORL DIRECT, #DATA
Logical Ex-OR
CPL A,
CPL C,
CPL bit address
SWAP A – Swap the upper nibble and lower nibble of A.
Rotate Instructions
RRA
This instruction is rotate right the accumulator. Its operation is illustrated below. Each bit is shifted one
location to the right, with bit 0 going to bit 7.
RL A
Rotate left the accumulator. Each bit is shifted one location to the left, with bit 7 going to bit 0
RRC A
Rotate right through the carry. Each bit is shifted one location to the right, with bit 0 going into the carry
bit in the PSW, while the carry was at goes into bit 7
RLC A
Rotate left through the carry. Each bit is shifted one location to the left, with bit 7 going into the carry bit
in the PSW, while the carry goes into bit 0.
5.5 JUMP, LOOP AND CALL Instructions
Repeating a sequence of instructions a certain number of times is called a loop. Loop action is performed
by
DJNZ Reg, Label
The register is decremented If it is not zero, it jumps to the target address referred to by the label .Prior to
the start of loop the register is loaded with the counter for the number of repetitions ƒ, Counter can be R0
– R7 or RAM location.
Nested Loop- If we want to repeat an action more times than 256, we use a loop inside a loop, which is called
nested loop .We use multiple registers to hold the count.
1. Only 1 byte of jump address needs to be specified in the 2's complement form, ie. For
jumping ahead, the range is 0 to 127 and for jumping back, the range is -1 to-128.
2. Specifying only one byte reduces the size of the instruction and speeds up program
execution.
3. The program with relative jumps can be relocated without reassembling to generate
absolute jump addresses.
JZ <relative address>
00 0000-07FF
01 0800 -0FFF
02 1000-17FF
03 1800 -1FFF
….
1E F000 -F7FF
1F F800 -FFFF
It can be seen that the upper 5 bits of the program counter (PC) hold the page number and the
lower 11bits of the PC hold the address within that page. Thus, an absolute address is formed by
taking page numbers of the instruction (from the program counter) following the jump and
attaching the specified 11bits to it to form the 16-bit address.
Advantage: The instruction length becomes 2 bytes. Example of short absolute jump: -
ACALL <address11>
AJMP <address11>
5.5.4 Long Absolute Jump/Call
Applications that need to access the entire program memory from 0000H to FFFFH use long absolute
jump. Since the absolute address has to be specified in the op-code, the instruction length is 3 bytes
(except for JMP @ A+DPTR). This jump is not re-locatable.
Example: -
LCALL <address 16>
LJMP <address 16>
JMP @A+DPTR
1. The unconditional jump is a jump in which control is transferred unconditionally to the target
location.
a. LJMP (long jump). This is a 3-byte instruction. First byte is the op-code and second
and third bytes represent the 16-bit target address which is any memory location from
0000 toFFFFH
eg: LJMP 3000H
b. AJMP: this causes unconditional branch to the indicated address, by loading the 11
bit address to 0-10 bits of the program counter. The destination must be there for
within the same 2K blocks.
c. SJMP (short jump). This is a 2-byte instruction. First byte is the op-code and second
byte is the relative target address, 00 to FFH (forward +127 and backward -128 bytes
from the current PC value). To calculate the target address of a short jump, the second
byte is added to the PC value which is address of the instruction immediately below
the jump.
Bit level JUMP instructions will check the conditions of the bit and if condition is true, it jumps to the
address specified in the instruction. All the bit jumps are relative jumps.
JBbit, rel ; jump if the direct bit is set to the relative address specified.
JNBbit,rel ;jump if the direct bit is clear to the relative address specified.
JBCbit,rel ; jump if the direct bit is set to the relative address specified and then clear the
bit.
Subroutines are handled by CALL and RET instructions. There are two types of CALL instructions
1. LCALL address(16bit)
This is long call instruction which unconditionally calls the subroutine located at the
indicated 16 bit address. This is a 3 byte instruction. The LCALL instruction works as
follows.
f. [PC]=address (16 bit);the new address of subroutine is loaded to PC. No flags are
affected.
2. ACALL address(11bit)
This is absolute call instruction which unconditionally calls the subroutine located at the
indicated 11 bit address. This is a 2 byte instruction. The SCALL instruction works as
follows.
P3.4 < T0 14
P3.5 < T1 15
P3.6 < WR 16
Dual role of Port 0 − Port 0 is also designated as AD0–AD7, as it can be used for both data and
address handling. While connecting an 8051 to external memory, Port 0 can provide both address
and data. The 8051 microcontroller then multiplexes the input as address or data in order to save
pins.
Dual role of Port 2 − Besides working as I/O, Port P2 is also used to provide 16-bit address bus for
external memory along with Port 0. Port P2 is also designated as (A8– A15), while Port 0 provides
the lower 8-bits via A0–A7. In other words, we can say that when an 8051 is connected to an
external memory (ROM) which can be maximum up to 64KB and this is possible by 16 bit address
bus because we know 216 = 64KB. Port2 is used for the upper 8-bit of the 16 bits address, and it
cannot be used for I/O and this is the way any Program code of external ROM is addressed.
PSEN or Program store Enable (Pin No 29) − This is also an active low pin, i.e., it gets activated
after applying a low pulse. It is an output pin and used along with the EA pin in 8031 based (i.e.
ROMLESS) Systems to allow storage of program code in external ROM.
ALE or (Address Latch Enable) − This is an Output Pin and is active high. It is especially used for
8031 IC to connect it to the external memory. It can be used while deciding whether P0 pins will be
used as Address bus or Data bus. When ALE = 1, then the P0 pins work as Data bus and when ALE
= 0, then the P0 pins act as Address bus.
Instructions Function
Timer in 8051 is used as timer, counter and baud rate generator. Timer always counts up
irrespective of whether it is used as timer, counter, or baud rate generator: Timer is always
incremented by the microcontroller. The time taken to count one digit up is based on master
clock frequency.
If Master CLK=12 MHz,
Timer Clock frequency=Master CLK/12=1MHz
Timer Clock Period=1microsecond
This indicates that one increment in count will take 1 micro second.
The two timers in 8051 share two SFRs (TMOD and TCON) which control the timers, and each
timer also has two SFRs dedicated solely to itself (TH0/TL0 and TH1/TL1).
TCON Register
5.7. 1 Timer/ Counter Control Logic.
The lower 5 bits of TLX and 8 bits of THX are used for the 13 bit count. Upper 3 bits of TLX are
ignored. When the counter rolls over from all 0's to all 1's, TFX flag is set and an interrupt is
generated. The input pulse is obtained from the previous stage. If TR1/0 bit is 1 and Gate bit is 0, the
counter continues counting up. If TR1/0 bit is 1 and Gate bit is 1, then the operation of the counter is
controlled by input. This mode is useful to measure the width of a given pulse fed to input.
TimerMode-1:This mode is similar to mode-0 except for the fact that the Timer operates in16-bit
mode.
Fig: Operation of Timer in Mode 1
Timer Mode-2: (Auto-Reload Mode): This is a 8 bit counter/timer operation. Counting is performed
in TLX while THX store a constant value. In this mode when the timer overflows i.e. TLX becomes
FFH, it is fed with the value stored in THX. For example if we load THX with 50H then the timer in
mode 2 will count from 50H to FFH. After that 50H is again reloaded. This mode is useful in
applications like fixed time sampling.
Timer Mode-3: Timer 1 in mode-3 simply holds its count. The effect is same as setting TR1=0. Timer0
in mode-3 establishes TL0 and TH0 as two separate counters.
Control bits TR1 and TF1 are used by Timer-0 (higher 8 bits) (TH0) in Mode-3 while TR0 and TF0
are available to Timer-0 lower 8 bits(TL0).
5.7.3 Programming 8051 Timers In Assembly
In order to program 8051 timers, it is important to know the calculation of initial count value to be
stored in the timer register. The calculations are as follows.
In any mode, Timer Clock period = 1/Timer Clock Frequency.
= 1/(Master Clock Frequency/12)
Mode 1:
Load the TMOD value register indicating which timer (0 or 1) is to be used
and which timer mode is selected.
Load registers TL and TH with initial count values.
Start the timer by the instruction “SETB TR0” for timer 0 and “SETB TR1” for
timer1.
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 becomeshigh.
Stop the timer with the instructions “CLR TR0” or “CLR TR1”, for timer 0 and
timer 1, respectively.
Clear the TF flag for the next round with the instruction “CLR TF0” or “CLR
TF1”,for timer 0 and timer 1,respectively.
Go back to step 2 to load TH and TL again.
Mode 0:
The programming techniques mentioned here are also applicable to counter/timer
mode 0. The only difference is in the number of bits of the initialization value.
Mode 2:
Load the TMOD value register indicating which timer (0 or 1) is to be used;
select timer mode2.
Load TH register with the initial count value. As it is an 8-bit timer, the valid
range is from 00 toFFH.
Start the timer.
Keep monitoring the timer flag (TFx) with the “JNB TFx,target” instruction to see
if it is raised. Get out of the loop when TFx goeshigh.
Clear the TFx flag.
Go back to step 4, since mode 2 is auto-reload.
Communication Links
1. Simplex communication link: In simplex transmission, the line is dedicated for transmission.
The transmitter sends and the receiver receives the data.
Transmitter Receiver
2. Half duplex communication link: In half duplex,the communication link can be used for either
transmission or reception. Data is transmitted in only one direction at a time.
Transmitter Receiver
Receiver Transmitter
3. Full duplex communication link: If the data is transmitted in both ways at the same time, it
is a full duplex i.e. transmission and reception can proceed simultaneously. This communication
link requires two wires for data, one for transmission and one for reception.
Transmitter Receiver
Receiver Transmitter
Data
Clock
2. Asynchronous Serial data transmission: In this, different clock sources are used for transmitter
and receiver. In this mode, data is transmitted with start and stop bits. A transmission begins with
start bit, followed by data and then stop bit. For error checking purpose parity bit is included just
prior to top bit. In Asynchronous serial data communication a single byte is transmitted at a time.
Transmitter Start D0 D1 D2 D3 D4 D5 D6 D7 D8 Stop Receiver
Data
Clock1 Clock2
Baud rate:
The rate at which the data is transmitted is called baud or transfer rate. The baud rate is the
reciprocal of the time to send one bit. In asynchronous transmission, baud rate is not equal to
number of bits per second. This is because; each byte is preceded by a start bit and followed by
parity and stop bit. For example, in synchronous transmission, if data is transmitted with 9600
baud, it means that 9600 bits are transmitted in one second. For bit transmission time = 1 second/
9600 = 0.104 ms.
5.8.6 Connectiontors-232
RS-232 Standards:
To allow compatibility among data communication equipment made by various manufactures, an
interfacing standard called RS232 was set by the Electronics Industries Association (EIA) in 1960.
Since the standard was set long before the advent of logic family, its input and output voltage levels
are not TTL compatible.
In RS232, a logic one (1) is represented by -3 to -25V and referred as MARK while logic zero (0) is
represented by +3 to +25V and referred as SPACE. For this reason to connect any RS232 to a
microcontroller system we must use voltage converters such as MAX232 to convert the TTL logic level
to RS232 voltage levels and vice-versa. MAX232 IC chips are commonly referred as line drivers.
In RS232 standard we use two types of connectors. DB9 connector or DB25 connector.
The 8051 has two pins that are used specifically for transferring and receiving data serially. These two
pins are called TXD, RXD. Pin 11 of the 8051 (P3.1) assigned to TXD and pin 10 (P3.0) is designated
as RXD. These pins TTL compatible; therefore they require line driver (MAX 232) to make them
RS232 compatible. MAX 232 converts RS232 voltage levels to TTL voltage levels and vice versa.
One advantage of the MAX232 is that it uses a +5V power source which is the same as the source
voltage for the 8051. The typical connection diagram between MAX 232 and 8051 is shown below.
Example1. Write a program for the 8051 to transfer letter ‘A’ serially at4800-baudrate, 8 bit data, 1
stop bit continuously.
ORG
0000H LJMP START ORG
0030H
START: MOVTMOD,#20H ; select timer 1 mode2
MOVTH1,#0FAH ; load count to get baud rate of
4800 MOVSCON,#50H ; initialize UART in mode2
; 8 bit data and 1 stop bit
SETBTR1 ; starttimer
AGAIN: MOVSBUF,#'A' ; load char ‘A’ inSBUF
BACK: JNB TI, BACK ; Check for transmit
interrupt flag CLRTI ; Clear transmit interrupt flag
SJMPAGAIN
END
Example2.Write a program for the 8051 to transfer the message ‘EARTH’ serially at 9600 baud,
8 bit data, 1 stop bit continuously.
ORG
0000H
LJMP
START
ORG 0030H
START: MOVTMOD,#20H ; select timer 1 mode2
MOVTH1,#0FDH ; load count to get reqd. baud rate of9600
MOVSCON,#50H ; initialise uart in mode2
; 8 bit data and 1 stopbit
SETBTR1 ; starttimer
LOOP: MOVA,#'E' ; load 1st letter ‘E’ in a
ACALLLOAD ; call load
subroutine MOVA, #'A' ; load 2nd letter ‘A’ in a
ACALLLOAD ; call load
subroutine MOVA,#'R' ; load 3rd letter ‘R’ in a
ACALLLOAD ; call load
subroutine MOVA,#'T' ; load 4th letter ‘T’ in a
ACALLLOAD ; call load
subroutine MOVA,#'H' ; load 4th letter ‘H’ in a
ACALLLOAD ; call loadsubroutine
SJMPLOOP ; repeatsteps
END
5.9 Interrupt Programming
5.9.1 Basics of Interrupts
During program execution if peripheral devices needs service from microcontroller, device will
generate interrupt and gets the service from microcontroller. When peripheral device activate the
interrupt signal, the processor branches to a program called interrupt service routine. After executing
the interrupt service routine the processor returns to the main program.
ISR will always ends with RETI instruction. The execution of RETI instruction results in the following.
IE Register
This is an 8 bit register used for enabling or disabling the interrupts. The structure of IE register
is shown below.
IP Register.
This is an 8 bit register used for setting the priority of the interrupts.
UNIVERSITY QUESTIONS RELATED TO THE TOPIC
Two-mark questions
Q-1. Define the term bit, byte, nibble, and word.
Q-2. What is the difference between microprocessor and microcomputer?
Q-3. Draw the block diagram of Microcomputer.
Q-4. What is the heart of computer system?
Q-5. What is Microprocessor?
Five-mark questions
Q-6. Explain the evolution of Microprocessor.
Q-7. Give the difference between machine language and assembly language.
Q-8. What is the Difference between RISC and CISC architecture?
Q-9. What is the difference between Von-Newman and Harvard architecture?
Q-10.Explain the characteristics of Microprocessor.
Ten-mark questions
Q-11. Explain the five applications of Microprocessor.
GATE questions
5.10 INTERFACING
Interfacing is one of the important concepts in microcontroller 8051 because the microcontroller
is a CPU that can perform some operation on a data and gives the output. However to perform
the operation we need an input device to enter the data and in turn output device displays the
results of the operation. Here we are using keyboard and LCD display as input and output
devices along with the microcontroller.
Interfacing is the process of connecting devices together so that they can exchange the
information and that proves to be easier to write the programs. There are different type of input
and output devices as for our requirement such as LEDs, LCDs, 7segment, keypad, motors and
other devices.
Here is given some important modules interfaced with microcontroller 8051.
5.11 LCD & KEYBOARD INTERFACING
LCD stands for liquid crystal display which can display the characters per line. Here 16 by 2
LCD display can display 16 characters per line and there are 2 lines. In this LCD each character
is displayed in 5*7 pixel matrix.
LCD is very important device which is used for almost all automated devices such as washing
machines, an autonomous robot, power control systems and other devices. This is achieved by
displaying their status on small display modules like 7-seven segment displays, multi segment
LEDs etc. The reasons being, LCDs are reasonably priced, easily programmable and they have a
no limitations of displaying special characters. It consists of two registers such as
command/instruction register and data register.
a. The command/instruction register stores the command instructions given to the
LCD. A command is an instruction which is given to the LCD that perform a set
of predefined tasks like initializing, clearing the screen, setting the cursor posing,
controlling display etc.
b. The data register stores the data to be displayed on LCD. The data is an ASCII
value of the characters to be displayed on the LCD.
Operation of LCD is controlled by two commands. When RS=0, R/W=1 it reads the data and
when RS=1, R/W=0, it writes (print) the data.
Circuit Diagram:
Source code:
#include<reg51.h>
#define kam P0
void lcd_initi();
void lcd_dat(unsigned char );
void lcd_cmd (unsigned char );
void delay(unsigned int );
void display(unsigned char *s, unsigned char r);
void main()
{
lcd_initi();
lcd_cmd(0x80);
delay(100);
display(“EDGEFX TECHLNGS”, 15);
lcd_cmd(0xc0);
display(“KITS & SOLTIONS”,15);
while(1);
}
void lcd_initi()
{
lcd_cmd(0x01);
delay(100);
lcd_cmd(0x38);
delay(100);
lcd_cmd(0x06);
delay(100);
lcd_cmd(0x0c);
delay(100);
}
void lcd_dat(unsigned char dat)
{
kam = dat;
rs=1;
rw=0;
en=1;
delay(100);
en=0;
}
void lcd_cmd(unsigned char cmd)
{
kam=cmd;
rs=0;
rw=0;
en=1;
delay(100);
en=0;
}
void delay( unsigned int n)
{
unsigned int a;
for(a=0;a<n;a++);
}
Description:
Keyboard is a widely used input device with lot of applications such as telephone, computer,
ATM, electronic lock etc. A keypad is used to take input from the user for further processing.
Here a 4 by 3 matrix keypad consisting of switches arranged in rows and columns is interfaced
to the microcontroller. A 16 by 2 LCD is also interfaced for displaying the output.
The interfacing concept of keypad is very simple. Every number of keypad is assigned two
unique parameters that are row and column (R, C). Hence every time a key is pressed the
number is identifying by detecting the row and column numbers of keypad.
Initially all the rows are set to zero (‘0’) by the controller and columns are scanned to check if
any key is pressed. In case of no key is pressed the output of all columns will be high (‘1’).
Circuit Diagram
Source Code:
#include<reg51.h>
#define kam P0
sbit rs=P2^0;
sbit rw=P2^1;
sbit en=P2^2;
sbit c1=P1^4;
sbit c2=P1^5;
sbit c3=P1^6;
sbit r1=P1^0;
sbit r2=P1^1;
sbit r3=P1^2;
sbit r4=P1^3;
void lcd_initi();
void lcd_dat(unsigned char );
void lcd_cmd (unsigned char );
void delay(unsigned int );
void display(unsigned char *s, unsigned char r);
void main()
{
lcd_initi();
lcd_cmd(0x80);
delay(100);
display(“0987654321”, 10);
while(1);
}
unsigned int w;
for(w=0;w<r;w++)
{
lcd_dat(s[w]);
}
}
void lcd_initi()
{
lcd_cmd(0x01);
delay(100);
lcd_cmd(0x38);
delay(100);
lcd_cmd(0x06);
delay(100);
lcd_cmd(0x0c);
delay(100);
}
en=1;
delay(100);
en=0;
}
void delay( unsigned int n)
{
unsigned int a;
for(a=0;a<n;a++);
}
}
2-3volt 010B
If you look at the table above, you will understand how the ADC maps analog data to digital
values. In the case mentioned above, we can see that the tiniest change we can detect is that of 1
volt. If the change is smaller than 1 volt, the ADC can’t detect it. This minimum change that an
ADC can detect is known as the step size of the ADC. To calculate it, we can use the formula:
Step size=Vmax-Vmin/2n (where n is the number of bits(resolution) of an ADC)
The step size of an ADC is inversely proportional to the number of bits of an ADC. So using an
ADC with higher bits can detect smaller changes, but this increases the cost of production. Due
to this reason, most on-chip ADCs’ have an 8-bit/10-bit resolution. Given below is the resolution
vs. step size for various configurations with a range of 0-5v input signal.
8 256 5/256=19.53
10 1024 5/1024=4.88
12 4096 5/4096=1.2
Connect the oscillator circuit to pins 19 and 20. This includes a crystal oscillator and two
capacitors of 22uF each. Connect them to the pins, as shown in the diagram.
Connect one end of the capacitor to the EA’ pin and the other to the resister. Connect this
resistor to the RST pin, as shown in the diagram.
We are using port 1 as the input port, so we have connected the output ports of the ADC
to port 1.
As mentioned earlier, the 0808 does not have an internal clock; therefore, we have to
connect an external clock. Connect the external clock to pin 10.
Connect Vref (+) to a voltage source according to the step size you need.
Ground Vref (-) and connect the analog sensor to any one of the analog input pins on the
ADC. We have connected a variable resistor to INT2 for getting a variable voltage at the
pin.
Connect ADD A, ADD B, ADD C, and ALE pins to the microcontroller for selecting the
input analog port. We have connected ADD A- P2.0; ADD B- P2.1; ADD C- P2.2 and
the ALE pin to port 2.4.
Connect the control pins Start, OE, and Start to the microcontroller. These pins are
connected as follows in our case Start-Port-2.6; OE-Port-2.5 and EOC-Port-2.7.
With this, you have successfully interfaced the 8051 to the ADC. Now let us look at the logic to
use the ADC with the microcontroller.
5.12.2 Logic to communicate between 8051 and ADC 0808
Several control signals need to be sent to the ADC to extract the required data from it.
Step 1: Set the port you connected to the output lines of the ADC as an input port. You
can learn more about the Ports in 8051 here.
Step 2: Make the Port connected to EOC pin high. The reason for doing this is that the
ADC sends a high to low signal when the conversion of data is complete. So this line
needs to be high so that the microcontroller can detect the change.
Step 3: Clear the data lines which are connected to pins ALE, START, and OE as all
these pins require a Low to High pulse to get activated.
Step 4: Select the data lines according to the input port you want to select. To do this,
select the data lines and send a High to Low pulse at the ALE pin to select the address.
Step 5: Now that we have selected the analog input pin, we can tell the ADC to start the
conversion by sending a pulse to the START pin.
Step 6: Wait for the High to low signal by polling the EOC pin.
Step 7: Wait for the signal to get high again.
Step 8: Extract the converted data by sending a High to low signal to the OE pin.
Now that we have a basic understanding of how to interface an ADC with the 8051, let us look
at an example in which we connect LEDs to 8051 to see the data conversion.
C program to interface ADC 0808 with 8051
The Digital to Analog converter (DAC) is a device, that is widely used for converting digital
pulses to analog signals. There are two methods of converting digital signals to analog signals.
These two methods are binary weighted method and R/2R ladder method. In this article we will
use the MC1408 (DAC0808) Digital to Analog Converter. This chip uses R/2R ladder method.
This method can achieve a much higher degree of precision. DACs are judged by its resolution.
The resolution is a function of the number of binary inputs. The most common input counts are
8, 10, 12 etc. Number of data inputs decides the resolution of DAC. So if there are n digital
input pin, there are 2n analog levels. So 8 input DAC has 256 discrete voltage levels.
The MC1408 DAC (or DAC0808)
In this chip the digital inputs are converted to current. The output current is known as Iout by
connecting a resistor to the output to convert into voltage. The total current provided by
the Iout pin is basically a function of the binary numbers at the input pins D0 - D7 (D0 is the LSB
and D7 is the MSB) of DAC0808 and the reference current Iref.
The Iref is the input current. This must be provided into the pin 14. Generally 2.0mA is used as
Iref
We connect the Iout pin to the resistor to convert the current to voltage. But in real life it may
cause inaccuracy since the input resistance of the load will also affect the output voltage. So
practically Iref current input is isolated by connecting it to an Op-Amp with Rf = 5KΩ as
feedback resistor. The feedback resistor value can be changed as per requirement.
Generating Sinewave using DAC and 8051 Microcontroller
For generating sinewave, at first we need a look-up table to represent the magnitude of the sine
value of angles between 0° to 360°. The sine function varies from -1 to +1. In the table only
integer values are applicable for DAC input. In this example we will consider 30° increments
and calculate the values from degree to DAC input. We are assuming full-scale voltage of 10V
for DAC output. We can follow this formula to get the voltage ranges.
Vout = 5V + (5 ×sinθ)
Let us see the lookup table according to the angle and other parameters for DAC.
Angle(in sinθ Vout (Voltage Values sent
θ) Magnitude) to DAC
0 0 5 128
90 1.0 10 255
180 0 5 128
270 -1.0 0 0
360 0 5 128
Circuit Diagram −
Source Code
#include<reg51.h>
sfr DAC = 0x80; //Port P0 address
void main(){
int sin_value[12] = {128,192,238,255,238,192,128,64,17,0,17,64};
int i;
while(1){
//infinite loop for LED blinking
for(i = 0; i<12; i++){
DAC = sin_value[i];
}
}
}
Output
The output will look like this −
5.13 Sensor Interfacing with 8051
Sensors are the electro-mechanical devices which converts the physical world parameters (air,
wind, speed, light, color..) into its corresponding electrical signals. Using sensors many
developments is been done. Mostly all the micro controllers are interfaced with sensors for a
particular task.
This is built around the IR-sensor and 8051 MCU and a 7-segment LED display, this will. Here
the IR-sensor detects the change in the variations in the light and gives a ON/OFF pulse. These
pulses are fed to the MCU and counts the number of pulses. Displays the count on 7-segment
LED display.
Digital sensors.
Analog Sensors.
Digital sensors:
This kind of sensors gives the ON/OFF pulses at the output side, which means 0V and 5V.
Basically, all the digital sensors are Analog in nature but in the back end these are interfaced to
comparators.
Examples:
IR-Sensor.
Ultrasonic sensor.
PIR sensor.
Proximity sensors.
Metal detectors.
Many more sensors are getting manufactured as per the requirements of users.
Analog Sensors:
These are not like digital sensors that is they could not give ON/OFF signals as output
instead they will produce a sinusoidal wave as output. These signals need some analog to digital
converters (ADC) for interfacing with MCU. Now a days mostly all the MCUs has its own ADC
channels, except for 8051 families there is no ADC block internally so analog sensors are to be
interfaced with ADC for 8051.
Examples:
Current sensor.
MEMS
Humidity sensor
Temperature sensor etc..
Caution:
While interfacing a sensor to 8051 the power supply should not exceed the ratings of the
sensor, this may damage the sensor.
“Note: Before using any sensor calibrate and check it, if it is working properly or not.”
Source code:
A stepper motor is one of the most commonly used motor for precise angular movement. The
advantage of using a stepper motor is that the angular position of the motor can be controlled
without any feedback mechanism. The stepper motors are widely used in industrial and
commercial applications. They are also commonly used as in drive systems such as robots,
washing machines etc.
Stepper motors can be unipolar or bipolar and here we are using unipolar stepper motor. The
unipolar stepper motor consists of six wires out of which four are connected to coil of the motor
and two are common wires. Each common wire is connected to a voltage source and remaining
wires are connected to the microcontroller.
Circuit Diagram:
Source code:
#include<reg51.h>
sbit a=P3^0;
sbit b=P3^1;
sbit c=P3^2;
sbit d=P3^3;
void delay();
void main()
{
while(1)
{
a=0;
b=1;
c=1;
d=1;
delay();
a=1;
b=0;
c=1;
d=1;
delay();
a=1;
b=1;
c=0;
d=1;
delay();
a=1;
b=1;
c=1;
d=0;
}
}
void delay()
{
Five-mark questions
Q-5. Explain in detail the assembler directives in 8051 along with suitable examples.
Q-6. What do you mean by logical operation in 8051?
Q-7. Explain the data manipulation instructions along with examples.
Q-8. Explain subroutine in 8051.
Q-9. Different between call and jump instruction by using suitable examples.