20201221-Complete Notes MCA
20201221-Complete Notes MCA
20201221-Complete Notes MCA
1
Microcontrollers and Applications
SYLLABUS
Course Objective:
This course introduces the architecture of 8051 Microcontroller, the instruction set of 8051, real-time
interrupts, real time Timers and interfacing with 8051 Microcontroller.
REFERENCES:
1. Kenneth. J. Ayala, “The 8051 Microcontroller”, Cengage Learning, 3rd Edition, 2004.
2. Microcontrollers (Theory & Applications) – A.V. Deshmuk, WTMH, 2005.
3. Design with PIC Microcontrollers – John B. Peatman, Pearson Education, 2005.
E-RESOURCES:
1. https://www.edgefx.in/8051-microcontroller-architecture/
2. http://www.newagepublishers.com/samplechapter/002079.pdf
3. http://8051-microcontrollers.blogspot.in/2015/11/timers-and-counterstimers.html#.WYbVGLpuLIU
104
2
Microcontrollers and Applications
4. http://ymk.k-space.org/Lecture_Nov5.pdf
5. http://www.rtcmagazine.com/technologies/view/Microcontrollers
6. http://www.satishkashyap.com/2012/02/video-lectures-on-microprocessors-and.html
Course Outcomes:
At the end of the course, students will be able to:
1. Describe the basic architecture of 8051microcontroller
2. Write assembly language programs for 8051 microcontroller.
3. Know the interrupt handling techniques.
4. Know the usage of timers in real time applications.
5. Develop a microcontroller based system.
3
Microcontrollers and Applications
UNIT - 1
MICROPROCESSORS AND MICROCONTROLLERS
Microprocessor Microcontroller
Accumulator Interrupt
Registers
Internal Circuits
Working Registers
Internal RAM ROM
Program Counter Stack Pointer Stack Pointer Clock
It has many instructions to move data between It has few instructions to move data between memory
memory and CPU and CPU
Less number of pins are multifunctional More number of pins are multifunctional
Single memory map for data and code Separate memory map for data and code (program)
(program)
Access time for memory and IO are more Less access time for built in memory and IO.
More flexible in the design point of view Less flexible since the additional circuits which is
residing inside the microcontroller is fixed for a
particular microcontroller
Large number of instructions with flexible Limited number of instructions with few
addressing modes addressing modes
4
Microcontrollers and Applications
RISC CISC
Only load/store instructions are used to access In additions to load and store instructions, memory
memory access is possible with other instructions also.
5
Microcontrollers and Applications
It uses single memory space for both It has separate program memory and data memory
instructions and data.
It is not possible to fetch instruction code and data Instruction code and data can be Fetched
simultaneously
Execution of instruction takes more machine cycle Execution of instruction takes less machine cycle
Also known as control flow or control driven Also known as data flow or data Driven
computers computers
Simplifies the chip design because of single memory Chip design is complex due to separate memory
space space
Eg. 8085, 8086, MC6800 Eg. General purpose microcontrollers, special DSP
chips etc.
6
Microcontrollers and Applications
COMPUTER SOFTWARE
A set of instructions written in a specific sequence for the computer to solve a specific task is called a
program and software is a collection of such programs.
The program stored in the computer memory in the form of binary numbers is called machine instructions.
The machine language program is called object code.
An assembly language is a mnemonic representation of machine language. Machine language and assembly
language are low level languages and are processor specific.
The assembly language program the programmer enters is called source code. The source code (assembly
language) is translated to object code (machine language) using assembler.
Programs can be written in high level languages such as C, C++ etc. High level language will be converted
to machine language using compiler or interpreter. Compiler reads the entire program and translate into
the object code and then it is executed by the processor. Interpreter takes one statement of the high level
language as input and translate it into object code and then executes.
7
Microcontrollers and Applications
I/O
A8-
Port 2 A1
5
ROM
PC DPTR
DPH I/O
INT
DPL Port 3 CNTR
SERIA
L
RD/W
R
E IE
ALE System General IP
Timing purpose PCON
PSEN
area SBUF
XTAL1 System SCON
XTAL2 TCON
Bit addressible
timers area TMOD
RESET TL0
Register Bank 3
Data TH0
Register Bank 2
buffers TL1
Register Bank 1
• 8051 has 4 K Bytes of internal ROM. The address space is from 0000 to 0FFFh. If the program
size is more than 4 K Bytes 8051 will fetch the code automatically from external memory.
• Accumulator is an 8 bit register widely used for all arithmetic and logical operations. Accumulator
is also used to transfer data between external memory. B register is used along with Accumulator
for multiplication and division. A and B registers together is also called MATH registers.
8
Microcontrollers and Applications
• PSW (Program Status Word). This is an 8 bit register which contains the arithmetic status of ALU
and the bank select bits of register banks.
CY AC F0 RS1 RS0 OV - P
CY - carry flag
AC - auxiliary carry flag
F0 - available to the user for general purpose
RS1,RS0 - register bank select bits
OV - overflow
P - parity
• Stack Pointer (SP) – it contains the address of the data item on the top of the stack. Stack may reside
anywhere on the internal RAM. On reset, SP is initialized to 07 so that the default stack will start
from address 08 onwards.
• Data Pointer (DPTR) – DPH (Data pointer higher byte), DPL (Data pointer lower byte). This is a
16 bit register which is used to furnish address information for internal and external program
memory and for external data memory.
• Program Counter (PC) – 16 bit PC contains the address of next instruction to be executed. On reset
PC will set to 0000. After fetching every instruction PC will increment by one.
PIN DIAGRAM
Pinout Description
Pins 1-8 PORT 1. Each of these pins can be configured as an input or an output.
Pin 9 RESET. A logic one on this pin disables the microcontroller and clears the contents of most
registers. In other words, the positive voltage on this pin resets the microcontroller. By
applying logic zero to this pin, the program starts execution from the beginning.
Pins10-17 PORT 3. Similar to port 1, each of these pins can serve as general input or output. Besides,
all of them have alternative functions
9
Microcontrollers and Applications
Pin 31 EA. By applying logic zero to this pin, P2 and P3 are used for data and address transmission
with no regard to whether there is internal memory or not. It means that even there is a
program written to the microcontroller, it will not be executed. Instead, the program written
to external ROM will be executed. By applying logic one to the EA pin, the microcontroller
will use both memories, first internal then external (if exists).
Pin 32-39 PORT 0. Similar to P2, if external memory is not used, these pins can be used as general
inputs/outputs. Otherwise, P0 is configured as address output (A0-A7) when the ALE pin is
driven high (1) or as data output (Data Bus) when the ALE pin is driven low (0).
10
Microcontrollers and Applications
MEMORY ORGANIZATION
Internal RAM organization
R7 1F
R6 1E
R5 1D
BANK 3
R4 1C 2F
7F 78 7F
R3 1B 77 70 7E
2E
R2 1A
6F 68 .
R1 19 2D
R0 18 67 60 .
2C
R7 17 5F 58 .
2B
R6 16
R5 15
57 50 .
BANK 2
2A
R4 14 29
4F 48 .
R3 13 47 40 .
28
R2 12
R1 11 27 3F 38 .
R0 10 26
37 30 .
R7 0F 2F 28
R6 0E 25 32
R5 0D 27 20
24 31
BANK 1
R4 0C 1F 18
R3 0B
23 30
17 10
R2 0A 22
R1 09 21 0F 08
R0 08 07 00
R7 07
20 General purpose memory
R6 06
R5 05
BANK 0
Working Registers
Register Banks: 00h to 1Fh. The 8051 uses 8 general-purpose registers R0 through R7 (R0, R1, R2, R3,
R4, R5, R6, and R7). There are four such register banks. Selection of register bank can be done through
RS1,RS0 bits of PSW. On reset, the default Register Bank 0 will be selected.
Bit Addressable RAM: 20h to 2Fh . The 8051 supports a special feature which allows access to bit
variables. This is where individual memory bits in Internal RAM can be set or cleared. In all there are 128
bits numbered 00h to 7Fh. Being bit variables any one variable can have a value 0 or 1. A bit variable can
be set with a command such as SETB and cleared with a command such as CLR. Example instructions
are:
SETB 25h ; sets the bit 25h (becomes 1)
CLR 25h ; clears bit 25h (becomes 0)
Note, bit 25h is actually bit 5 of Internal RAM location 24h.
The Bit Addressable area of the RAM is just 16 bytes of Internal RAM located between 20h and 2Fh.
General Purpose RAM: 30h to 7Fh. Even if 80 bytes of Internal RAM memory are available for
general-purpose data storage, user should take care while using the memory location from 00 -2Fh
11
Microcontrollers and Applications
since these locations are also the default register space, stack space, and bit addressable space. It is a good
practice to use general purpose memory from 30 – 7Fh. The general purpose RAM can be accessed using
direct or indirect addressing modes.
Number of address lines required for 16 Kbyte memory is 14 lines and that of 32Kbytes of memory is 15
lines.
PSEN PSEN
A14
A13
A13
A12 A12
A12
… .. 32 Kbyte
A9 A8
A8
WE
. RAM
WR 16 Kbyte .
RD OE
A3
AL A7 RAM A2
LE ..
8051 A0-A7 A0-A7 A1
A1
A0
A0
LOWER BYTE
EA ADDRESS
GND [AD0 – AD7] DAT DAT
A A
O/P O/P
AD0
- DATA BUS [AD0 – AD7]
AD7
The lower order address and data bus are multiplexed. De-multiplexing is done by the latch. Initially the
address will appear in the bus and this latched at the output of latch using ALE signal. The output of the
latch is directly connected to the lower byte address lines of the memory. Later data will be available in this
bus. Still the latch output is address it self. The higher byte of address bus is directly connected to the
memory. The number of lines connected depends on the memory size.
The RD and WR (both active low) signals are connected to RAM for reading and writing the data.
PSEN of microcontroller is connected to the output enable of the ROM to read the data from the memory.
EA (active low) pin is always grounded if we use only external memory. Otherwise, once the program size
exceeds internal memory the microcontroller will automatically switch to external memory.
12
Microcontrollers and Applications
STACK
A stack is a last in first out memory. In 8051 internal RAM space can be used as stack. The address of the
stack is contained in a register called stack pointer. Instructions PUSH and POP are used for stack
operations. When a data is to be placed on the stack, the stack pointer increments before storing the data on
the stack so that the stack grows up as data is stored (pre-increment). As the data is retrieved from the stack
the byte is read from the stack, and then SP decrements to point the next available byte of stored data (post
decrement). The stack pointer is set to 07 when the 8051 resets. So that default stack memory starts from
address location 08 onwards (to avoid overwriting the default register bank ie., bank 0).
Timer Counter
Maximum count rate is 1/12 of Maximum count rate is 1/24 of the oscillator
13
Microcontrollers and Applications
Timer 1 Register
The 16-bit register of Timer 1 is accessed as low- and high-byte. The low-byte register is called TL1
(Timer 1 low byte) and the high-byte register is called TH1 (Timer 1 high byte). These registers can be
accessed like any other register. For example, the instruction MOV TL1, #4H moves the value into the
low-byte of Timer 1.
14
Microcontrollers and Applications
Gate − When set, the timer only runs while INT(0,1) is high.
C/T − Counter/Timer select bit.
M1 − Mode bit 1.
M0 − Mode bit 0.
GATE
Every timer has a means of starting and stopping. Some timers do this by software, some by hardware,
and some have both software and hardware controls. 8051 timers have both software and hardware
controls. The start and stop of a timer is controlled by software using the instruction SETB TR1 and CLR
TR1 for timer 1, and SETB TR0 and CLR TR0 for timer 0.
The SETB instruction is used to start it and it is stopped by the CLR instruction. These instructions start
and stop the timers as long as GATE = 0 in the TMOD register. Timers can be started and stopped by an
external source by making GATE = 1 in the TMOD register.
C/T (CLOCK / TIMER)
This bit in the TMOD register is used to decide whether a timer is used as a delay generator or an event
manager. If C/T = 0, it is used as a timer for timer delay generation. The clock source to create the time
delay is the crystal frequency of the 8051. If C/T = 0, the crystal frequency attached to the 8051 also
decides the speed at which the 8051 timer ticks at a regular interval.
Timer frequency is always 1/12th of the frequency of the crystal attached to the 8051. Although various
8051 based systems have an XTAL frequency of 10 MHz to 40 MHz, we normally work with the XTAL
frequency of 11.0592 MHz. It is because the baud rate for serial communication of the 8051.XTAL =
11.0592 allows the 8051 system to communicate with the PC with no errors.
M1 / M2
M1 M2 Mode
15
Microcontrollers and Applications
1 1 Spilt mode.
16
Microcontrollers and Applications
When Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be set in modes 0, 1 or 2, but it
cannot be started/stopped as the bits that do that are now linked to TH0. The real timer 1 will be
incremented with every machine cycle.
Initializing a Timer
Decide the timer mode. Consider a 16-bit timer that runs continuously, and is independent of any external
pins.
Initialize the TMOD SFR. Use the lowest 4 bits of TMOD and consider Timer 0. Keep the two bits, GATE
0 and C/T 0, as 0, since we want the timer to be independent of the external pins. As 16-bit mode is timer
mode 1, clear T0M1 and set T0M0. Effectively, the only bit to turn on is bit 0 of TMOD. Now execute
the following instruction −
MOV TMOD,#01h
Now, Timer 0 is in 16-bit timer mode, but the timer is not running. To start the timer in running mode, set
the TR0 bit by executing the following instruction −
SETB TR0
Now, Timer 0 will immediately start counting, being incremented once every machine cycle.
Reading a Timer
A 16-bit timer can be read in two ways. Either read the actual value of the timer as a 16-bit number, or
you detect when the timer has overflowed.
Detecting Timer Overflow
When a timer overflows from its highest value to 0, the microcontroller automatically sets the TFx bit in
the TCON register. So instead of checking the exact value of the timer, the TFx bit can be checked. If TF0
is set, then Timer 0 has overflowed; if TF1 is set, then Timer 1 has overflowed.
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.
17
Microcontrollers and Applications
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
18
Microcontrollers and Applications
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 stop bit. In
Asynchronous serial data communication a single byte is transmitted at a time.
19
Microcontrollers and Applications
3. PCON register: The SMOD bit (bit 7) of PCON register controls the baud rate in asynchronous
mode transmission.
20
Microcontrollers and Applications
4. Mode 3
This is similar to mode 2 except baud rate is calculated as in mode 1
CONNECTIONS TO RS-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.
21
Microcontrollers and Applications
ORG 0000H
LJMP
START
ORG 0030H
START: MOV TMOD, #20H ; select timer 1 mode 2
MOV TH1, #0FAH ; load count to get baud rate of 4800
MOV SCON, #50H ; initialize UART in mode 2
; 8 bit data and 1 stop bit
SETB TR1 ; start timer
AGAIN: MOV SBUF, #'A' ; load char ‘A’ in SBUF
BACK: JNB TI, BACK ; Check for transmit interrupt flag
CLR TI ; Clear transmit interrupt flag
SJMP AGAIN
END
Example 2. 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
22
Microcontrollers and Applications
START
23
Microcontrollers and Applications
ORG 0030H
START: MOV TMOD, #20H ; select timer 1 mode 2
MOV TH1, #0FDH ; load count to get reqd. baud rate of 9600
MOV SCON, #50H ; initialise uart in mode 2
; 8 bit data and 1 stop bit
SETB TR1 ; start timer
LOOP: MOV A, #'E' ; load 1st letter ‘E’ in a
ACALL LOAD ; call load subroutine
MOV A, #'A' ; load 2nd letter ‘A’ in a
ACALL LOAD ; call load subroutine
MOV A, #'R' ; load 3rd letter ‘R’ in a
ACALL LOAD ; call load subroutine
MOV A, #'T' ; load 4th letter ‘T’ in a
ACALL LOAD ; call load subroutine
MOV A, #'H' ; load 4th letter ‘H’ in a
ACALL LOAD ; call load subroutine
SJMP LOOP ; repeat steps
END
Interrupts:
An interrupt is a signal to the processor emitted by hardware or software indicating an event that needs
immediate attention. Whenever an interrupt occurs, the controller completes the execution of the current
instruction and starts the execution of an Interrupt Service Routine (ISR) or Interrupt Handler. ISR
tells the processor or controller what to do when the interrupt occurs. The interrupts can be either hardware
interrupts or software interrupts.
Hardware Interrupt
A hardware interrupt is an electronic alerting signal sent to the processor from an external device, like a
disk controller or an external peripheral. For example, when we press a key on the keyboard or move the
mouse, they trigger hardware interrupts which cause the processor to read the keystroke or mouse position.
Software Interrupt
A software interrupt is caused either by an exceptional condition or a special instruction in the instruction
set which causes an interrupt when it is executed by the processor. For example, if the processor's
arithmetic logic unit runs a command to divide a number by zero, to cause a divide-by-zero exception,
thus causing the computer to abandon the calculation or display an error message. Software interrupt
instructions work similar to subroutine calls.
What is Polling?
24
Microcontrollers and Applications
The state of continuous monitoring is known as polling. The microcontroller keeps checking the status of
other devices; and while doing so, it does no other operation and consumes all its processing time for
monitoring. This problem can be addressed by using interrupts.
In the interrupt method, the controller responds only when an interruption occurs. Thus, the controller is
not required to regularly monitor the status (flags, signals etc.) of interfaced and inbuilt devices.
Interrupts v/s Polling
Here is an analogy that differentiates an interrupt from polling −
Interrupt Polling
25
Microcontrollers and Applications
Reset 0000 9
• When the reset pin is activated, the 8051 jumps to the address location 0000. This is power-up
reset.
• Two interrupts are set aside for the timers: one for timer 0 and one for timer 1. Memory locations
are 000BH and 001BH respectively in the interrupt vector table.
• Two interrupts are set aside for hardware external interrupts. Pin no. 12 and Pin no. 13 in Port 3
are for the external hardware interrupts INT0 and INT1, respectively. Memory locations are 0003H
and 0013H respectively in the interrupt vector table.
• Serial communication has a single interrupt that belongs to both receive and transmit. Memory
location 0023H belongs to this interrupt.
Steps to Execute an Interrupt
When an interrupt gets active, the microcontroller goes through the following steps −
• The microcontroller closes the currently executing instruction and saves the address of the next
instruction (PC) on the stack.
• It also saves the current status of all the interrupts internally (i.e., not on the stack).
• It jumps to the memory location of the interrupt vector table that holds the address of the interrupts
service routine.
• The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it. It
starts to execute the interrupt service subroutine, which is RETI (return from interrupt).
26
Microcontrollers and Applications
• Upon executing the RETI instruction, the microcontroller returns to the location where it was
interrupted. First, it gets the program counter (PC) address from the stack by popping the top bytes
of the stack into the PC. Then, it start to execute from that address.
Edge Triggering vs. Level Triggering
Interrupt modules are of two types − level-triggered or edge-triggered.
If the interrupt source is still asserted Edge-triggered interrupt modules can be acted
when the firmware interrupt handler immediately, no matter how the interrupt source
handles the interrupt, the interrupt behaves.
module will regenerate the interrupt,
causing the interrupt handler to be
invoked again.
• EA − Global enable/disable.
• - − Undefined.
• ET2 − Enable Timer 2 interrupt.
27
Microcontrollers and Applications
28
Microcontrollers and Applications
inside interrupt. In 8051, a low-priority interrupt can be interrupted by a high-priority interrupt, but not
by any another low-priority interrupt.
Triggering an Interrupt by Software
There are times when we need to test an ISR by way of simulation. This can be done with the simple
instructions to set the interrupt high and thereby cause the 8051 to jump to the interrupt vector table. For
example, set the IE bit as 1 for timer 1. An instruction SETB TF1 will interrupt the 8051 in whatever it
is doing and force it to jump to the interrupt vector table.
I/O Ports:
8051 microcontroller have 4 I/O ports each of 8-bit, which can be configured as input or output. Hence,
total 32 I/O pins allows the microcontroller to be connected with the peripheral devices.
1) PORT 0
P0 can be used as a bidirectional I/O port or it can be used for address/data connected for accessing
external memory. When control is 1 the port is used for address or data interfacing. When the control is 0
then the port can be used as a bidirectional I/O port.
If the control is 0 then the port is used as an input port and 1 is written to the latch. In this type of
situation both the output MOSFETs are off. Since the output pin has floats therefore, whatever data
written on pin is directly read by read pin.
If we want to write 1 on pin of P0, a '1' written to the latch which turns 'off' the lower FET while due to
'0' control signal upper FET also turns off.
Suppose we want to write '0' on pin of port 0, when '0' is written to the latch, the pin is pulled down
by the lower FET. Hence the output becomes zero.
29
Microcontrollers and Applications
2) PORT 1
PORT 1 is dedicated only for I/O interfacing. When used as an output port, not needed to connect
additional pull-up resistor like port 0.
To use PORT 1 as an input port '1' has to be written to the latch. In this mode 1 is written to the pin by
the external device then it read fine.
3) PORT 2
PORT 2 is used for higher external address byte or a normal I/O port. Here, the I/O operation is similar to
PORT 1. Latch of PORT 2 remains stable when Port 2 pin are used for external memory access.
4) PORT 3
30
Microcontrollers and Applications
P3.4 T0 Timer 0
P3.5 T1 Timer 1
It works as an I/O port same like port 2. Alternate functions of port 3 makes its architecture different than
other ports.
31
Microcontrollers and Applications
UNIT 2
INSTRUCTION SYNTAX.
General syntax for 8051 assembly language is as follows.
LABEL : (THIS IS NOT NECESSARY UNLESS THAT SPECIFIC LINE HAS TO BE ADDRESSED). 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 some cases 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.
ADDRESSING MODES
Various methods of accessing the data are called addressing modes.
1. Immediate addressing.
2. Register addressing.
3. Direct addressing.
4. Indirect addressing.
5. Relative addressing.
6. Absolute addressing.
7. Long addressing.
8. Indexed addressing.
9. Bit inherent addressing.
10. Bit direct addressing.
1. Immediate addressing.
In this addressing mode the data is provided as a part of instruction itself. In other words data
immediately follows the instruction.
Eg. MOV A,#30H
ADD A, #83 # Symbol indicates the data is immediate.
32
Microcontrollers and Applications
2. Register addressing.
In this addressing mode the register will hold the data. One of the eight general registers (R0 to R7)
can be used and specified as the operand.
Eg. MOV A,R0
ADD A,R6
R0 – R7 will be selected from the current selection of register bank. The default register bank will be bank 0.
3. Direct addressing
There are two ways to access the internal memory. Using direct address and indirect address. Using direct
addressing mode we can not only address the internal memory but SFRs also. In direct addressing, an 8 bit internal
data memory address is specified as part of the instruction and hence, it can specify the address only in the range of
00H to FFH. In this addressing mode, data is obtained directly from the memory.
Eg. MOV A,60h
ADD A,30h
4. Indirect addressing
The indirect addressing mode uses a register to hold the actual address that will be used in data movement.
Registers R0 and R1 and DPTR are the only registers that can be used as data pointers. Indirect addressing cannot be
used to refer to SFR registers. Both R0 and R1 can hold 8 bit address and DPTR can hold 16 bit address.
Eg. MOV A,@R0
ADD A,@R1
MOVX A,@DPTR
5. Indexed addressing.
In indexed addressing, either the program counter (PC), or the data pointer (DTPR)—is used to
hold the base address, and the A is used to hold the offset address. Adding the value of the base address to
the value of the offset address forms the effective address. Indexed addressing is used with JMP or MOVC
instructions. Look up tables are easily implemented with the help of index addressing.
Eg. MOVC A, @A+DPTR // copies the contents of memory location pointed by the sum of the accumulator
A and the DPTR into accumulator A.
MOVC A, @A+PC // copies the contents of memory location pointed by the sum of the
accumulator A and the program counter into accumulator A.
6. Relative Addressing.
Relative addressing is used only with conditional jump instructions. The relative address, (offset),
is an 8 bit signed number, which is automatically added to the PC to make the address of the next
instruction. The 8 bit signed offset value gives an address range of +127 to —128 locations. The jump
destination is usually specified using a label and the assembler calculates the jump offset accordingly.
The advantage of relative addressing is that the program code is easy to relocate and the address is
relative to position in the memory.
Eg: SJMP LOOP1
JC BACK
7. Absolute addressing
Absolute addressing is used only by the AJMP (Absolute Jump) and ACALL (Absolute Call)
instructions. These are 2 bytes instructions. The absolute addressing mode specifies the lowest 11 bit of
the memory. The upper 5 bit of the destination address are the upper 5 bit of the current program
counter. Hence, absolute addressing allows branching only within the current 2 Kbyte page of the
program memory.
Eg. AJMP LOOP1
33
Microcontrollers and Applications
ACALL LOOP2
8. Long Addressing
The long addressing mode is used with the instructions LJMP and LCALL. These are 3 byte
instructions. The address specifies a full 16 bit destination address so that a jump or a call can be made
to a location within a 64 Kbyte code memory space.
Eg. LJMP FINISH
LCALL DELAY
INSTRUCTION SET
1. Instruction Timings
The 8051 internal operations and external read/write operations are controlled by the oscillator clock.
T-state, Machine cycle and Instruction cycle are terms used in instruction timings.
T-state is defined as one subdivision of the operation performed in one clock period. The terms 'T- state' and
'clock period' are often used synonymously.
Machine cycle is defined as 12 oscillator periods. A machine cycle consists of six states and each state
lasts for two oscillator periods. An instruction takes one to four machine cycles to execute an
instruction.
Instruction cycle is defined as the time required for completing the execution of an instruction. The 8051
instruction cycle consists of one to four machine cycles.
Eg. If 8051 microcontroller is operated with 12 MHz oscillator, find the execution time for the following
four instructions.
1. ADD A, 45H
2. SUBB A, #55H
3. MOV DPTR, #2000H
4. MUL AB
Since the oscillator frequency is 12 MHz, the clock period is, Clock period = 1/12 MHz = 0.08333 µS. Time for 1
machine cycle = 0.08333 µS x 12 =1 µS.
Instruction No. of machine cycles Execution time
1. ADD A, 45H 1 1 µs
2. SUBB A, #55H 2 2 µs
3. MOV DPTR, #2000H 2 2 µs
4. MUL AB 4 4 µs
34
Microcontrollers and Applications
2. 8051 Instructions
The instructions of 8051 can be broadly classified under the following headings.
1. Data transfer instructions
2. Arithmetic instructions
3. Logical instructions
4. Branch instructions
5. Subroutine instructions
6. Bit manipulation instructions
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 iii. MOV 45H, A
ii. MOV A, iv. MOV @R1, A
@R0
35
Microcontrollers and Applications
i. MOVX A,@R1
ii. MOVX @R0,A
h. Move the contents of program memory to A
i. MOVC A, @A+PC
ii. MOVC A, @A+DPTR
MOVX A,@DPTR
iii. MOVX@DPTR,A
Arithmetic instructions.
The 8051 can perform addition, subtraction. Multiplication and division operations on 8 bit numbers.
Addition
In this group, we have instructions to
i. Add the contents of A with immediate data with or without carry.
i. ADD A, #45H
ii. ADDC A, #OB4H
ii. Add the contents of A with register Rn with or without carry.
i. ADD A, R5
ii. ADDC A, R2
iii. Add the contents of A with contents of memory with or without carry using direct and indirect
addressing
i. ADD A, 51H
ii. ADDC A, 75H
iii. ADD A, @R1
iv. ADDC A, @R0
36
Microcontrollers and Applications
i. SUBB A, R5
ii. SUBB A, R2
iii. Subtract the contents of A with contents of memory with or without carry using direct and indirect
addressing
i. SUBB A, 51H
ii. SUBB A, 75H
iii. SUBB A, @R1
iv. SUBB A, @R0
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] = 45 x F5 = 4209
;[A]=09H, [B]=42H
Division
37
Microcontrollers and Applications
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. MOV A,#45H ;[A]=0E8H
MOV B,#0F5H ;[B]=1BH
DIV AB ;[A] / [B] = E8 /1B = 08 H with remainder 10H
;[A] = 08H, [B]=10H
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.
• If lower nibble is greater than 9 or auxiliary carry is 1, 6 is added to lower nibble.
• If upper nibble is greater than 9 or carry is 1, 6 is added to upper nibble.
Eg 1: MOV A,#23H
MOV R1,#55H
ADD A,R1 // [A]=78
DA A // [A]=78 no changes in the accumulator after da a
Eg 2: MOV A,#53H
MOV R1,#58H
ADD A,R1 // [A]=ABh
DA A // [A]=11, C=1 . ANSWER IS 111. Accumulator data is changed after DA A
INC increments the value of source by 1. 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.
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
Logical AND
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,
38
Microcontrollers and Applications
leaving the resulting value in destination. The value in source is not affected. " OR " instruction
logically OR the bits of source and destination.
ORL A,#DATA ORL A, Rn
ORL A,DIRECT ORL
A,@Ri
ORL DIRECT,A ORL DIRECT, #DATA
Logical Ex-OR
XRL destination, source: XRL does a bitwise "EX-OR" operation between source and
destination, leaving the resulting value in destination. The value in source is not affected. " XRL "
instruction logically EX-OR the bits of source and destination.
XRL A,#DATA XRL A,Rn
XRL A,DIRECT XRL
A,@Ri
XRL DIRECT,A XRL DIRECT, #DATA
Logical NOT
CPL complements operand, leaving the result in operand. If operand is a single bit then the state of the bit
will be reversed. If operand is the Accumulator then all the bits in the Accumulator will be reversed.
Rotate Instructions
RR A
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.
39
Microcontrollers and Applications
Relative Jump
Jump that replaces the PC (program counter) content with a new address that is greater than (the address
following the jump instruction by 127 or less) or less than (the address following the jump by 128 or less)
is called a relative jump. Schematically, the relative jump can be shown as follows: -
40
Microcontrollers and Applications
In 8051, 64 kbyte of program memory space is divided into 32 pages of 2 kbyte each. The hexadecimal
addresses of the pages are given as follows:-
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 5bits 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.
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: -
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 to FFFFH
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 therefore 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.
41
Microcontrollers and Applications
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.
JB bit, rel ; jump if the direct bit is set to the relative address specified. JNB
bit, rel ; jump if the direct bit is clear to the relative address specified.
JBC bit, rel ; jump if the direct bit is set to the relative address specified and then clear the bit.
42
Microcontrollers and Applications
f. [PC10-0]= address (11 bit); the new address of subroutine is loaded to PC. No flags are
affected.
RET instruction
RET instruction pops top two contents from the stack and load it to PC.
g. [PC15-8] = [[SP]];content of current top of the stack will be moved to higher byte of PC.
h. [SP]=[SP]-1; (SP decrements)
i. [PC7-0] = [[SP]] ;content of bottom of the stack will be moved to lower byte of PC.
j. [SP]=[SP]-1; (SP decrements again)
8051 has 128 bit addressable memory. Bit addressable SFRs and bit addressable PORT pins. It is possible to perform
following bit wise operations for these bit addressable locations.
1. LOGICAL AND
a. ANL C,BIT(BIT ADDRESS) ; ‘LOGICALLY AND’ CARRY AND CONTENT OF BIT ADDRESS, STORE RESULT IN CARRY
b. ANL C, /BIT; ; ‘LOGICALLY AND’ CARRY AND COMPLEMENT OF CONTENT OF BIT ADDRESS, STORE RESULT IN CARRY
2. LOGICAL OR
a. ORL C,BIT(BIT ADDRESS) ; ‘LOGICALLY OR’ CARRY AND CONTENT OF BIT ADDRESS, STORE RESULT IN CARRY
b. ORL C, /BIT; ; ‘LOGICALLY OR’ CARRY AND COMPLEMENT OF CONTENT OF BIT ADDRESS, STORE RESULT IN CARRY
3. CLR bit
a. CLR bit ; CONTENT OF BIT ADDRESS SPECIFIED WILL BE CLEARED.
b. CLR C ; CONTENT OF CARRY WILL BE CLEARED.
4. CPL bit
a. CPL bit ; CONTENT OF BIT ADDRESS SPECIFIED WILL BE COMPLEMENTED.
b. CPL C ; CONTENT OF CARRY WILL BE COMPLEMENTEd
ASSEMBLER DIRECTIVES
Assembler directives tell the assembler to do something other than creating the machine code for an
instruction. In assembly language programming, the assembler directives instruct the assembler to
1. Process subsequent assembly language instructions
2. Define program constants
3. Reserve space for variables
ORG (origin)
The ORG directive is used to indicate the starting address. It can be used only when the
program counter needs to be changed. The number that comes after ORG can be either in hex
or in decimal.
Eg: ORG 0000H ;Set PC to 0000
43
Microcontrollers and Applications
END
The END directive signals the end of the assembly module. It indicates the end of the program to
the assembler. Any text in the assembly file that appears after the END directive is ignored. If the
END statement is missing, the assembler will generate an error message.
44
Microcontrollers and Applications
1. Write a program to add the values of locations 50H and 51H and store the result in locations in 52h
and 53H.
2. Write a program to store data FFH into RAM memory locations 50H to 58H using direct
addressing mode
3. Write a program to subtract a 16 bit number stored at locations 51H-52H from 55H-56H and store
the result in locations 40H and 41H. Assume that the least significant byte of data or the result is
stored in low address. If the result is positive, then store 00H, else store 01H in 42H. ORG 0000H
; Set program counter 0000H
MOV A, 55H ; Load the contents of memory location 55 into A
CLR C ; Clear the borrow flag
SUBB A,51H ; Sub the contents of memory 51H from contents of A
MOV 40H, A ; Save the LSByte of the result in location 40H
MOV A, 56H ; Load the contents of memory location 56H into A
SUBB A, 52H ; Subtract the content of memory 52H from the content A
MOV 41H, ; Save the MSbyte of the result in location 415.
MOV A, #00 ; Load 005 into A
ADDC A, #00 ; Add the immediate data and the carry flag to A MOV
42H, A ; If result is positive, store00H, else store 0lH in 42H
END
45
Microcontrollers and Applications
4. Write a program to add two 16 bit numbers stored at locations 51H-52H and 55H-56H and store
the result in locations 40H, 41H and 42H. Assume that the least significant byte of data and the
result is stored in low address and the most significant byte of data or the result is stored in high
address.
5. Write a program to store data FFH into RAM memory locations 50H to 58H using indirect
addressing mode.
ORG 0000H ; Set program counter 0000H
MOV A, #0FFH ; Load FFH into A
MOV RO, #50H ; Load pointer, R0-50H
MOV R5, #08H ; Load counter, R5-08H
Start:MOV @RO, A ; Copy contents of A to RAM pointed by R0
INC RO ; Increment pointer
DJNZ R5, start ; Repeat until R5 is zero
END
6. Write a program to add two Binary Coded Decimal (BCD) numbers stored at locations 60H and
61H and store the result in BCD at memory locations 52H and 53H. Assume that the least
significant byte of the result is stored in low address.
46
Microcontrollers and Applications
47
Microcontrollers and Applications
DJNZ R5,Loop
DIV AB
MOV 55H,A
END
12. Write a program to find the cube of an 8 bit number program is as follows
ORG 0000H
MOV
R1,#N
MOV A,R1
MOV B,R1
MUL AB //SQUARE IS
COMPUTED MOV R2, B
MOV B, R1
MUL AB
MOV 50,A
MOV 51,B
MOV A,R2
MOV B, R1
MUL AB
ADD A, 51H
MOV 51H,
A MOV 52H,
B MOV A, #
00H ADDC
A, 52H
MOV 52H, A //CUBE IS STORED IN
52H,51H,50H END
13. Write a program to exchange the lower nibble of data present in external memory 6000H and 6001H
ORG 0000H ; S e t p r o g r a m c o u n t e r 0 0h
MOV DPTR, # 6000 H ; Copy address 6000 H to DPTR
MOVX A, @DPTR ; Copy contents of 60008 to A
MOV R0, #45H ; Load pointer, R0=45H
MOV @RO, A ; Copy cont of A to RAM pointed by 80
INC DPL ; Increment pointer
MOVX A, @DPTR ; Copy contents of 60018 to A
XCHD A, @R0 ;ExchangelowernibbleofAwithRAMpointedbyR O
14. Write a program to count the number of and o's of 8 bit data stored in location 6000H.
ORG 00008 ; Set program counter 00008
MOV DPTR, #6000h ; Copy address 6000H to DPTR
MOVX A, @DPTR ; Copy num be r t o A
MOV R0,#08 ; Copy 08 in RO
MOV R2,#00 ; C o py 00 in R 2
MOV R3,#00 ; C o py 00 in R 3
CLR C ; Clear carry flag
BACK: RLC A ; Rotate A through carry flag
48
Microcontrollers and Applications
JC NEXT ;IfCF=1,branchtonext
INC R2 ; I f C F = 0 , i n c r e m e n t R 2 AJMP
NEXT2 NEXT: INC R3 ; I f C F = 1 , i n c r e m e n t R3
NEXT2: DJNZ RO,BACK ; Repeat until RO is zero
END
15. Write a program to shift a 24 bit number stored at 57H-55H to the left logically four places.
Assume that the least significant byte of data is stored in lower address.
ORG 0000H ; Set program counter 0000h
MOV R1,#04 ; Set up loop count to 4
again: MOV A,55H ; Place the least significant byte of data in A
CLR C ; Clear tne carry flag
RLC A ; Rotate contents of A (55h) left through carry
MOV 55H,A
MOV A,56H
RLC A ; Rotate contents of A (56H) left through carry
MOV 56H,A
MOV A,57H
RLC A ; Rotate contents of A (57H) left through carry
MOV 57H,A
DJNZ R1,again ; Repeat until R1 is zero
END
16. Two 8 bit numbers are stored in location 1000h and 1001h of external data memory. Write
a program to find the GCD of the numbers and store the result in 2000h. ALGORITHM
• Step 1 :Initialize external data memory with data and DPTR with address
• Step 2 :Load A and TEMP with the operands
• Step 3 :Are the two operands equal? If yes, go to step 9
• Step 4 :Is (A) greater than (TEMP) ? If yes, go to step 6
• Step 5 :Exchange (A) with (TEMP) such that A contains the bigger number
• Step 6 :Perform division operation (contents of A with contents of TEMP)
• Step 7 :If the remainder is zero, go to step 9
• Step 8 :Move the remainder into A and go to step 4
• Step 9 :Save the contents 'of TEMP in memory and terminate the program
ORG 0000H ; Set program counter 0000H
TEMP EQU 70H
TEMPI EQU 71H
MOV DPTR, #1000H ; Copy address 100011 to DPTR
MOVX A, @DPTR ; Copy First number to A
MOV TEMP, A ; Copy First number to temp INC DPTR
MOVX A, @DPTR ; Copy Second number to A
LOOPS: CJNE A, TEMP, LOOP1 ; (A) /= (TEMP) branch to LOOP1
AJMP LOOP2 ; (A) = (TEMP) branch to L00P2
LOOP1: JNC LOOP3 ; (A) > (TEMP) branch to LOOP3
NOV TEMPI, A ; (A) < (TEMP) exchange (A) with (TEMP)
MOV A, TEMP
MOV TEMP, TEMPI
LOOP3: MOV B, TEMP
DIV AB ; Divide (A) by (TEMP)
MOV A, B ; Move remainder to A
CJNE A,#00, LOOPS ; (A)/=00 branch to LOOPS
LOOP2: MOV A, TEMP
MOV DPTR, #2000H
MOVX @DPTR, A ; Store the result in 2000H
END
49
Microcontrollers and Applications
UNIT- 3
REAL TIME CONTROL –INTERRUPTS
3.1 INTERRUPT HANDLING STRUCTURE
• ENABLE/MASK
o Primary Level
o Secondary Level
• PRIORITY ASSIGNMENT
3.2 ROUTINE
• A SUBPROGRAM OR PROCEDURE OR SUB ROUTINE IMPLEMENTED BY
CALL AND RETURN
50
Microcontrollers and Applications
51
Microcontrollers and Applications
o Example:
▪ Latency of serial port interrupt should be less than 11/9600
second of interrupts are occurring every 11/9600 second
Td < Tlat
3.7 MULTIPLE SOURCES OF INTERRUPTS
• INTERNAL (TO overflow in 8051)
• EXTERNAL (INTO in 8051)
• HARDWARE
• SOFTWARE
52
Microcontrollers and Applications
53
Microcontrollers and Applications
54
Microcontrollers and Applications
o Let us take four interrupt sources INT1, INT2, INT3, INT4. Services
are ISR1, ISR2, ISR3, ISR4. ISR1 has highest priority.
▪ ISR3 under service. Execution Time of 2ms left at t
▪ At t4 ISR4 is pending since 1ms
▪ INT1 occurs at t – Its execution time is 5 ms
Therefore latency for INT4 = 1+2+5 = 8 ms
Latency for INT1 = 0
(Neglecting context switching)
▪ INT3 restarts after 5ms takes 7ms to complete
55
Microcontrollers and Applications
• CONCLUSION
▪ ISR1 done immediately
▪ ISR4 is affected badly. It can be serviced earlier by user
assigned higher priority
▪ DIAGRAM TO FOLLOW
ISR3 executing
t
2 ms
ISR1 executing
1 ms
5 ms
Int1 occurs
Remaining ISR3
2 ms
ISR4
8 ms (latency for INT4)
INT4 occurs
5 ms
ISR4 executing
8 ms (latency for int4)
INT4 occurs
56
Microcontrollers and Applications
57
Microcontrollers and Applications
58
Microcontrollers and Applications
UNIT 4
o Start/Stop
▪ Ex 1: In 8051 set TRO=1 for starting timer 0
▪ Ex 2: In 68HC11/12 it is not programmable as timer is free
running
o Programming Pre-Scaler
▪ Ex 1: In 8051 it is not programmable, It is fixed as 12
▪ Ex 2: In 8096 it is not programmable, it is fixed at 8
▪ In 68HC11/68HC12 it is programmable by two bits PR0 &
PR1.
So four factors – they are 1,4,8 & 16.
o Programming inputs of timer at start (Pre loading timers)
▪ Ex 1: 8051 has the facility. TL0 & TH0 to be loaded with
initial
non zero value. Let value be X after (2n-1-x) pulses , outputs will
be 1s. After (2n-x) pulses all outputs will become 0 (TL0 and
TH0 will also become 0). It is called overflow.
▪ Ex 2 : In 68HC11 this feature is not available as it is free
running
o Auto Loading inputs
▪ After one cycle of counts i.e. when over flow occurs, inputs
will be loaded again automatically and cycle repeats
59
Microcontrollers and Applications
o Programmable timers not ideal for real time control as time is lost
between start/stop. (latency of ISR introduces delay in case of
interrupt driven timer
o Free running counter is ideal for real time control as no time is lost
o It does not have start/stop and preloading the input facility
o Once it starts on power up, it keeps running
o It is like needle of a clock
o A watch is like three free running counter one for second, one for
minute and one for hour
Sequence of steps to move a robotic arm every 16 seconds using output compare
Register and 16 bit free running counter receiving pulses every 2ms.
• Assumptions
• To start with we start robot arm and after 8000000pulses we stop robot
arm
60
Microcontrollers and Applications
• After 16 seconds the timer count should be overflow 122 times and
should
• During first ISR1 when M1=FF disable interrupts and load OC register.
Now enable interrupts
• Now robot arm is started during first ISR1. Since timer is free running it
would have advanced to a value x. Hence for 16 second calculation x
should be added to 1200H I.E. 16 seconds will be completed after timer
reaches the value x+1200H. Put the value x+1200 in OC register
4.6 Sequence of steps to find time taken by weight lifter in lifting the weight
• Assumptions
o ISR3 executed on timer overflow. It updates M1 to keep track of
overflows
o ISR4 executed on input capture interrupt. It captures counts into a
register
61
Microcontrollers and Applications
• Real time clock interrupts are generated by using free running timer or
counter with a known clock signal
• The time never stops and cannot be reset or preloaded
• The input clock can be pre scaled by a factor, 1,4,8,16 etc . Pre scaling
means division of the clock
• RTCs will initiate an ISR which can be used to maintain system time
continuously. After updating timing information it enables next RTC
interrupt. ISR Can also be used to perform a specific task
• Operating System can use these interrupts to initiate number of the tasks
in a sequence
62
Microcontrollers and Applications
4.9 REAL TIME CLOCK INTERRUPTS USING OUTPUT COMPARE (IF RTC
FEATURE IS NOT THERE THEN OC FEATURE CAN BE USED AS IN 80X96)
• Timer based RTC interrupts depend on 2n*R*T and hence some specific
value
of R. Here R is a pre-scalar and width of the timer and T is input clock
period
• In 68HC11 N=13, R=1,2,4 or 8
• In OC based RTC interrupt, interrupts can be programmed with any value
i.e.
X and intervals at which interrupts occur will be X*T where T is input clock
period to free running counter and X is between 0 and 65536
4.11 SOFTWARE TIMERS
63
Microcontrollers and Applications
• SWT interrupt is where timer shows the count value = X. Where X can be
defined
at any instant and it can have any value between 0 and 65536
• Similarly software timer defers from over flow interrupt in the sense that it
has a distinct vector address when an ISR is initiated after equality of specific
count
value and out of timer. Whereas overflow interrupt occurs only after 216*P*T
where P is fixed in 80X96 and T is the duration of clock pulse. P is
programmable in 68 HC11. Software timer can be defined on quick
successions by defining different count values.
• Software defers from output compare interrupt in the sense that OC
interrupt initiates an ISR where an output bit is set or reset for external
control. Where as
in software timer interrupt ISR executes or initiates a specific user task
4.13 INTERRUPT INTERVAL AND DENSITY CONSTRAINTS
64
Microcontrollers and Applications
• 8BIT timer receiving input pulses at 4 Microsec interval. Find preload value
so
that it times out after 100microsecond. 100Microsecond/4Microsecond = 25, it
should overflow after 25 pulses. So preload value should be (256-25) =
231=E7H
• In above example if input is 1MicroscaledSec then it should be prescaled by a
factor of 4 so that P*T = 4Microsec therefore P=4 since T=1. This is assuming
that preload value is (256-25) i.e. overflow after 25 pulses
• In 8051 prescale factor is not there interrupt has to be generated after
100Microsecond , the following program has to be written
▪ Assume FOSC = 12MHZ
Clock to timer is fOSC/12 = 1MHZ
Hence pulse width = 1Microsec
Now timer zero to overflow after 100 pulse. So load (256-100) as preload
value i.e.156 or 9CH.
o Program timer 0 in mode 3 so that TL0 and TH0 can be used as 2
independent 8 bit timers use TL0 here
o Load TL0 with 9C
o Enable timers 0 for overflow interrupt
o Run timer by setting TR0
o Program
MOV TL0,#9CH
MOV TMOD,#03H
MOV IE,#82H
SETB TR0
Notes
1. If timer has to be reloaded. Stop timer and reload and start again
65
Microcontrollers and Applications
o EXAMPLE
Now after first overflow don’t send a 0 bit to stop robotic arm. It
should stop after 5th overflow. So timer is programmed without
auto reload capacity. If P.T. = 8Microsec i.e. P=8, T=1, then total
time elapsed will be (4*65536 + 1024) * 8 = 2.1seconds
PROGRAM
▪ Reset Timer
▪ Initialize TMOD,TL0,TH0
▪ Enable interrupt
▪ Run timer
▪ CLR P1.0 (Take action)
▪ Self Loop (Wait for interrupt)
• ISR
66
Microcontrollers and Applications
o INC M1
o CJNE M1,#N,EXIT
o SETB P1.1
o RETI
o EXIT: SETB TR0
o RETI
PROGRAM
▪ Timer 0
• Reset timer 0
• Use timer 0 in mode 1 as counter
• Initialize timer 0 (TL0,TH0)
• Run timer 0
▪ Timer 1
• Reset timer 1
• Use timer 1 in mode 1 as timer
• Initialize time 1 with y (TL0,TH0)
• Enable interrupt
• Run timer 1
• Self loop
▪ ISR for timer 1
• sStop timer 1
• Increment M, check if M = 0, if yes read timer 0
• Store TL0,TH0 in memory (This gives you
revolution/second)
67
Microcontrollers and Applications
Watchdog timer:
A Watchdog Timer is a circuit that automatically invokes a reset unless the system being watched sends regular
hold-off signals to the Watchdog.
Watchdog Circuit To make sure that a particular program is executing properly the Watchdog circuit is used. For
instance the program may reset a particular flip-flop periodically. And the flip-flop is set by an external circuit.
Suppose the flip-flop is not reset for long time it can be known by using external hardware. This will indicate that
the program is not executed properly and hence an exception or interrupt can be generated. Watch Dog
Timer(WDT) provides a unique clock, which is independent of any external clock. When the WDT is enabled, a
counter starts at 00 and increments by 1 until it reaches FF. When it goes from FF to 00 (which is FF + 1) then the
processor will be reset or an exception will be generated. The only way to stop the WDT from resetting the
processor or generating an exception or interrupt is to periodically reset the WDT back to 00 throughout the
program. If the program gets stuck for some reason, then the WDT will not be set. The WDT will then reset or
interrupt the processor. An interrupt service routine will be invoked to take into account the erroneous operation of
the program. (getting stuck or going into infinite loop).
68
Microcontrollers and Applications
69
Microcontrollers and Applications
70
Microcontrollers 4 Sem ECE
UNIT 5
When we press a pushbutton or toggle switch or a micro switch, two metal parts come into contact to short the
supply. But they don’t connect instantly but the metal parts connect and disconnect several times before the actual
stable connection is made. The same thing happens while releasing the button. This results the false triggering or
multiple triggering like the button is pressed multiple times. Its like falling a bouncing ball from a height and it
keeps bouncing on the surface, until it comes at rest.
Simply, we can say that the switch bouncing is the non-ideal behavior of any switch which generates multiple
transitions of a single input. Switch bouncing is not a major problem when we deal with the power circuits, but it
cause problems while we are dealing with the logic or digital circuits. Hence, to remove the bouncing from the
circuit Switch Debouncing Circuit is used.
Debouncing occurs in software also, while programming programmers add delays to get rid of software debouncing.
Adding a delay force the controller to stop for a particular time period, but adding delays is not a good option into
the program, as it pause the program and increase the processing time. The best way is to use interrupts in the code
for software bouncing. Arduino have code to prevent the software bouncing.
You can also see the waveform in oscilloscope while push button in bouncing. It shows that how much bouncing
has occurred during the switching of the pushbutton.
There are three commonly used methods to prevent the circuit from switch bouncing.
▪ Hardware Debouncing
▪ RC Debouncing
Saneesh Cleatus Thundiyil
BMS Institute of Technology, Bangalore – 64 71
Microcontrollers 4 Sem ECE
▪ Switch Debouncing IC
1. Hardware Debouncing
In the hardware debouncing technique we use an S-R flip flop to prevent the circuit from switch bounces. This is the
best debouncing method among all.
Components Required
▪ Nand Gate IC 74HC00
▪ Toggle Switch
▪ Resistor (10k -2nos.)
▪ Capacitor (0.1uf)
▪ LED
▪ Breadboard
Circuit Diagram
2. R-C Debouncing
The R-C is defined by its name only, the circuit used a RC network for the protection from switch bounce. The
capacitor in the circuit filter the instant changes in the switching signal. When the switch is in open state the voltage
across the capacitor remain zero. Initially, when the switch is open the capacitor charge through the R1 and R2
resistor.
When the switch is closed the capacitor starts discharging to zero hence the voltage at input terminal of the inverting
Schmitt trigger is zero, so the output becomes HIGH.
In the bouncing condition, the capacitor stops the voltage at Vin until it reaches to Vcc or Ground. To increase the
speed of RC debouncing we can connect a diode as shown in the below image. Thus, it reduces the charging time of
the capacitor.
3. Switch Debouncing IC
There are ICs available in market for switch debouncing. Some of the debouncing ICs are MAX6816, MC14490,
and LS118.Below is the circuit diagram for switch debouncing using MAX6818.
Light Emitting Diodes or LEDs are the mostly commonly used components in many applications. They are made of
semiconducting material. In this, It describe about basics of Interfacing LED with 8051 Microcontroller. Principle
behind Interfacing LED with 8051.The main principle of this circuit is to interface LEDs to the 8051 family micro
controller. Commonly, used LEDs will have voltage drop of 1.7v and current of 10mA to glow at full intensity. This
is applied through the output pin of the micro controller.
In this circuit, LEDs are connected to the port P0. The controller is connected with external crystal oscillator to pin
18 and 19 pins. Crystal pins are connected to the ground through capacitors of 33pf.
Light Emitting Diodes are the semi conductor light sources. Commonly used LEDs will have a cut-off voltage of
1.7V and current of 10mA. When an LED is applied with its required voltage and current it glows with full
intensity.
The Light Emitting Diode is similar to the normal PN diode but it emits energy in the form of light. The color of
light depends on the band gap of the semiconductor. The following figure shows “how an LED glows?”
Thus, LED is connected to the AT89C51 microcontroller with the help of a current limiting resistor. The value of
this resistor is calculated using the following formula.
Generally, microcontrollers output a maximum voltage of 5V. Thus, the value of resistor calculated for this is 330
Ohms. This resistor can be connected to either the cathode or the anode of the LED.
LCD display is an inevitable part in almost all embedded projects and this article is about interfacing a 16×2 LCD
with 8051 microcontroller. Many guys find it hard to interface LCD module with the 8051 but the fact is that if you
learn it properly, its a very easy job and by knowing it you can easily design embedded projects like digital voltmeter
/ ammeter, digital clock, home automation displays, status indicator display, digital code locks, digital
speedometer/ odometer, display for music players etc etc. Thoroughly going through this article will make you able
to display any text (including the extended characters) on any part of the 16×2 display screen. In order to understand
the interfacing first you have to know about the 16×2 LCD module.
16×2 LCD module is a very common type of LCD module that is used in 8051 based embedded projects. It consists
of 16 rows and 2 columns of 5×7 or 5×8 LCD dot matrices. The module were are talking about here is type number
JHD162A which is a very popular one . It is available in a 16 pin package with back light ,contrast adjustment
function and each dot matrix has 5×8 dot resolution. The pin numbers, their name and corresponding functions are
shown in the table below.
4 RS Register selection
6 E Enable
7 DB0 Data
8 DB1 Data
9 DB2 Data
10 DB3 Data
11 DB4 Data
12 DB5 Data
13 DB6 Data
14 DB7 Data
VEE pin is meant for adjusting the contrast of the LCD display and the contrast can be adjusted by varying the
voltage at this pin. This is done by connecting one end of a POT to the Vcc (5V), other end to the Ground and
connecting the center terminal (wiper) of of the POT to the VEE pin. See the circuit diagram for better understanding.
The JHD162A has two built in registers namely data register and command register. Data register is for placing the
data to be displayed , and the command register is to place the commands. The 16×2 LCD module has a set of
commands each meant for doing a particular job with the display. We will discuss in detail about the commands
later. High logic at the RS pin will select the data register and Low logic at the RS pin will select the command
register. If we make the RS pin high and the put a data in the 8 bit data line (DB0 to DB7) , the LCD module
will recognize it as a data to be displayed . If we make RS pin low and put a data on the data line, the module will
recognize it as a command.
R/W pin is meant for selecting between read and write modes. High level at this pin enables read mode and low
level at this pin enables write mode.
E pin is for enabling the module. A high to low transition at this pin will enable the module.
DB0 to DB7 are the data pins. The data to be displayed and the command instructions are placed on these pins.
LED+ is the anode of the back light LED and this pin must be connected to Vcc through a suitable series current
limiting resistor. LED- is the cathode of the back light LED and this pin must be connected to ground.
16×2 LCD module has a set of preset command instructions. Each command will make the module to do a
particular task. The commonly used commands and their function are given in the table below.
Command Function
01 Clear screen
02 Return home
04 Decrement cursor
06 Increment cursor
LCD initialization.
The steps that has to be done for initializing the LCD display is given below and these steps are common for
almost all applications.
The steps for sending data to the LCD module is given below. I have already said that the LCD module has pins
namely RS, R/W and E. It is the logic state of these pins that make the module to determine whether a given data
input is a command or data to be displayed.
Circuit diagram.
The circuit diagram given above shows how to interface a 16×2 LCD module with AT89S1 microcontroller.
Capacitor C3, resistor R3 and push button switch S1 forms the reset circuitry. Ceramic capacitors C1,C2 and
crystal X1 is related to the clock circuitry which produces the system clock frequency. P1.0 to P1.7 pins of the
microcontroller is connected to the DB0 to DB7 pins of the module respectively and through this route the data
goes to the LCD module. P3.3, P3.4 and P3.5 are connected to the E, R/W, RS pins of the microcontroller and
through this route the control signals are transffered to the LCD module. Resistor R1 limits the current through the
back light LED and so do the back light intensity. POT R2 is used for adjusting the contrast of the display.
Program for interfacing LCD to 8051 microcontroller is shown below.
Program.
MOV A,#67D
ACALL DISP
MOV A,#73D
ACALL DISP
MOV A,#82D
ACALL DISP
MOV A,#67D
ACALL DISP
MOV A,#85D
ACALL DISP
MOV A,#73D
ACALL DISP
MOV A,#84D
ACALL DISP
MOV A,#83D
ACALL DISP
MOV A,#84D
ACALL DISP
MOV A,#79D
ACALL DISP
MOV A,#68D
ACALL DISP
MOV A,#65D
ACALL DISP
MOV A,#89D
ACALL DISP
Saneesh Cleatus Thundiyil
BMS Institute of Technology, Bangalore – 64 79
Microcontrollers 4 Sem ECE
DISP:MOV P1,A
SETB P3.5
CLR P3.4
SETB P3.3
CLR P3.3
ACALL DELY
RET
CLR P3.3
CLR P3.4
RET
END
Subroutine CMND sets the logic of the RS, R/W, E pins of the LCD module so that the module recognizes the
input data ( given to DB0 to DB7) as a command.Subroutine DISP sets the logic of the RS, R/W, E pins of the
module so that the module recognizes the input data as a data to be displayed .
Interfacing LCD Module to 8051 in 4 Bit Mode (using only 4 pins of a port)
The microcontroller like 8051 has only limited number of GPIO pins (GPIO – general purpose input output). So to
design complex projects we need sufficient number of I/O pins . An LCD module can be interfaced with a
microcontroller either in 8 bit mode (as seen above) or in 4 bit mode. 8 bit mode is the conventional mode which
uses 8 data lines and RS, R/W, E pins for functioning. However 4 bit mode uses only 4 data lines along with the
control pins. This will saves the number of GPIO pins needed for other purpose.
Objectives
• Use a single port of the microcontroller for both data and control lines of the LCD.
As shown in the circuit diagram, port 0 of the controller is used for interfacing it with LCD module. In 4 bit mode
only 4 lines D4-D7, along with RS, R/W and E pins are used. This will save us 4 pins of our controller which we
might employ it for other purpose. Here we only need to write to the LCD module. So the R/W pin can be ground it
as shown in the schematic diagram. In this way the total number of pins can be reduced to 6. In 4 Bit mode the data
bytes are split into two four bits and are transferred in the form of a nibble. The data transmission to a LCD is
performed by assigning logic states to the control pins RS and E. The reset circuit, oscillator circuit and power supply
need to be provided for the proper working of the circuit.
Program – Interface LCD Module to 8051 – 4 Bit Mode
RS EQU P0.4
EN EQU P0.5
PORT EQU P0
U EQU 30H
L EQU 31H
ORG 000H
MOV DPTR,#INIT_COMMANDS
ACALL LCD_CMD
MOV DPTR,#LINE1
ACALL LCD_CMD
MOV DPTR,#TEXT1
ACALL LCD_DISP
MOV DPTR,#LINE2
ACALL LCD_CMD
MOV DPTR,#TEXT2
ACALL LCD_DISP
SJMP $
RET
LCD_CMD: CLR A
MOVC A,@A+DPTR
JZ EXIT2
INC DPTR
CLR RS
ACALL SPLITER
MOV A,U
ACALL MOVE
MOV A,L
ACALL MOVE
SJMP LCD_CMD
EXIT2: RET
LCD_DATA: SETB RS
ACALL SPLITER
MOV A,U
ACALL MOVE
MOV A,L
ACALL MOVE
RET
LCD_DISP: CLR A
MOVC A,@A+DPTR
JZ EXIT1
INC DPTR
ACALL LCD_DATA
SJMP LCD_DISP
EXIT1: RET
INIT_COMMANDS: DB 20H,28H,0CH,01H,06H,80H,0
LINE1: DB 01H,06H,06H,80H,0
LINE2: DB 0C0H,0
CLEAR: DB 01H,0
END
interfacing a hex key pad to 8051 microcontroller. A clear knowledge on interfacing hex key pad to 8051 is very
essential while designing embedded system projects which requires character or numeric input or both. For example
projects like digital code lock, numeric calculator etc. Before going to the interfacing in detail, let’s have a look at
the hex keypad.
Hex keypad.
Hex key pad is essentially a collection of 16 keys arranged in the form of a 4×4 matrix. Hex key pad usually have
keys representing numerics 0 to 9 and characters A to F. The simplified diagram of a typical hex key pad is shown
in the figure below.
Hex keypad
The hex keypad has 8 communication lines namely R1, R2, R3, R4, C1, C2, C3 and C4. R1 to R4 represents the
four rows and C1 to C4 represents the four columns. When a particular key is pressed the corresponding row and
column to which the terminals of the key are connected gets shorted. For example if key 1 is pressed row R1 and
column C1 gets shorted and so on. The program identifies which key is pressed by a method known as column
scanning. In this method a particular row is kept low (other rows are kept high) and the columns are checked for
low. If a particular column is found low then that means that the key connected between that column and the
corresponding row (the row that is kept low) is been pressed. For example if row R1 is initially kept low and column
C1 is found low during scanning, that means key 1 is pressed.
The circuit diagram for demonstrating interfacing hex keypad to 8051 is shown below.Like previous 8051 projects,
AT89S51 is the microcontroller used here. The circuit will display the character/numeric pressed on a seven segment
LED display. The circuit is very simple and it uses only two ports of the microcontroller, one for the hex keypad and
the other for the seven segment LED display.
ORG 00H
MOV DPTR,#LUT // moves starting address of LUT to DPTR
MOV A,#11111111B // loads A with all 1's
MOV P0,#00000000B // initializes P0 as output port
MOV A,#6D
ACALL DISPLAY
NEXT7:JB P1.7,NEXT8
MOV A,#7D
ACALL DISPLAY
NEXT8:SETB P1.1
CLR P1.2
JB P1.4,NEXT9
MOV A,#8D
ACALL DISPLAY
NEXT9:JB P1.5,NEXT10
MOV A,#9D
ACALL DISPLAY
NEXT10:JB P1.6,NEXT11
MOV A,#10D
ACALL DISPLAY
NEXT11:JB P1.7,NEXT12
MOV A,#11D
ACALL DISPLAY
NEXT12:SETB P1.2
CLR P1.3
JB P1.4,NEXT13
MOV A,#12D
ACALL DISPLAY
NEXT13:JB P1.5,NEXT14
MOV A,#13D
ACALL DISPLAY
NEXT14:JB P1.6,NEXT15
MOV A,#14D
ACALL DISPLAY
NEXT15:JB P1.7,BACK
MOV A,#15D
ACALL DISPLAY
LJMP BACK
DISPLAY:MOVC A,@A+DPTR // gets digit drive pattern for the current key from LUT
MOV P0,A // puts corresponding digit drive pattern into P0
RET
DB 11111100B
DB 10001110B
DB 01111010B
END
interface a seven segment LED display to an 8051 microcontroller. 7 segment LED display is very popular and it
can display digits from 0 to 9 and quite a few characters like A, b, C, ., H, E, e, F, n, o,t,u,y, etc. Knowledge about
how to interface a seven segment display to a micro controller is very essential in designing embedded systems. A
seven segment display consists of seven LEDs arranged in the form of a squarish ‘8’ slightly inclined to the right
and a single LED as the dot character. Different characters can be displayed by selectively glowing the required LED
segments. Seven segment displays are of two types, common cathode and common anode. In common cathode type
, the cathode of all LEDs are tied together to a single terminal which is usually labeled as ‘com‘ and the anode of
all LEDs are left alone as individual pins labeled as a, b, c, d, e, f, g & h (or dot) . In common anode type, the anode
of all LEDs are tied together as a single terminal and cathodes are left alone as individual pins. The pin out scheme
and picture of a typical 7 segment LED display is shown in the image below.
Digit drive pattern of a seven segment LED display is simply the different logic combinations of its terminals ‘a’
to ‘h‘ in order to display different digits and characters. The common digit drive patterns (0 to 9) of a seven segment
display are shown in the table below.
Digit a b c d e f g
0 1 1 1 1 1 1 0
1 0 1 1 0 0 0 0
2 1 1 0 1 1 0 1
3 1 1 1 1 0 0 1
4 0 1 1 0 0 1 1
5 1 0 1 1 0 1 1
6 1 0 1 1 1 1 1
7 1 1 1 0 0 0 0
8 1 1 1 1 1 1 1
9 1 1 1 1 0 1 1
The circuit diagram shown above is of an AT89S51 microcontroller based 0 to 9 counter which has a 7 segment
LED display interfaced to it in order to display the count. This simple circuit illustrates two things. How to setup
simple 0 to 9 up counter using 8051 and more importantly how to interface a seven segment LED display to 8051
in order to display a particular result. The common cathode seven segment display D1 is connected to the Port 1 of
the microcontroller (AT89S51) as shown in the circuit diagram. R3 to R10 are current limiting resistors. S3 is the
reset switch and R2,C3 forms a debouncing circuitry. C1, C2 and X1 are related to the clock circuit. The software
part of the project has to do the following tasks.
All the above said tasks are accomplished by the program given below.
Program.
Instruction MOVC A,@A+PC is the instruction that produces the required digit drive pattern for the display.
Execution of this instruction will add the value in the accumulator A with the content of the program counter(address
of the next instruction) and will move the data present in the resultant address to A. After this the program resumes
from the line after MOVC A,@A+PC.
In the program, initial value in A is 00001001B. Execution of MOVC A,@A+PC will add oooo1001B to the
content in PC ( address of next instruction). The result will be the address of label DB 3FH (line15) and the data
present in this address ie 3FH (digit drive pattern for 0) gets moved into the accumulator. Moving this pattern in the
accumulator to Port 1 will display 0 which is the first count.
At the next count, value in A will advance to 00001010 and after the execution of MOVC A,@+PC ,the value in A
will be 06H which is the digit drive pattern for 1 and this will display 1 which is the next count and this cycle gets
repeated for subsequent counts.
The reason why accumulator is loaded with 00001001B (9 in decimal) initially is that the instructions from line 9
to line 15 consumes 9 bytes in total.
The lines 15 to 24 in the program which starts with label DB can be called as a Look Up Table (LUT). label DB is
known as Define Byte – which defines a byte. This table defines the digit drive patterns for 7 segment display as
bytes (in hex format). MOVC operator fetches the byte from this table based on the result of adding PC and contents
in the accumulator.
Register B is used as a temporary storage of the initial value of the accumulator and the subsequent increments made
to accumulator to fetch each digit drive pattern one by one from the look up table(LUT).
Note:- In line 6, Accumulator is incremented by 1 each time (each loop iteration) to select the next digit drive pattern.
Since MOVC operator uses the value in A to fetch the digit drive pattern from LUT, value in ACC has to be
incremented/manipulated accordingly. The digit drive patterns are arranged consecutively in LUT.
Register R0 is used as a counter which counts from 10 down to 0. This ensures that digits from o to 9 are
continuously displayed in the 7 segment LED. You may note lines 4, 11, 12, and 13 in the above program. Line 4
initializes R0 to 10 (OAh). When the program counter reaches line 11 for the first time, 7 segment LED has already
Saneesh Cleatus Thundiyil
BMS Institute of Technology, Bangalore – 64 89
Microcontrollers 4 Sem ECE
displayed 0. So we can reduce one count and that is why we have written DEC Ro. We need to continuously check
if R0 has reached full count (that is 0). In order to do that lines 12 and 13 are used. We move R0 to accumulator and
then use the Jump if Zero (JZ) instruction to check if accumulator has reached zero. If Acc=0, then we makes the
program to jump to START (initial state) and hence we restart the 7 segment LED to display from 0 to 9 again. If
Acc not equal to zero, we continue the program to display the next digit (check line 14).
The Microcontroller does not provide sufficient current to drive motor and to safeguard 8081 from loading
effect and burn out condition, a motor driver IC ULN 2003 between 8051 and stepper motor. ULN 2003 is a
stepper motor driver.
1. Position control
2. Direction control &
3. Speed control
Stepper motors are basically two types: Unipolar and Bipolar. Unipolar stepper motor generally has five or six
wire, in which four wires are one end of four stator coils, and other end of the all four coils is tied together which
represents fifth wire, this is called common wire (common point). Generally there are two common wire, formed
by connecting one end of the two-two coils as shown in below figure. Unipolar stepper motor is very common and
popular because of its ease of use.
In Bipolar stepper motor there is just four wires coming out from two sets of coils, means there are no common
wire.
Stepper motor is made up of a stator and a rotator. Stator represents the four electromagnet coils which remain
stationary around the rotator, and rotator represents permanent magnet which rotates. Whenever the coils energised
by applying the current, the electromagnetic field is created, resulting the rotation of rotator (permanent magnet).
Coils should be energised in a particular sequence to make the rotator rotate. On the basis of this “sequence” we can
divide the working method of Unipolar stepper motor in three modes: Wave drive mode, full step drive mode and
half step drive mode.
In this type of functioning, the following 4 binary sequence/code are used for rotation: (Considering step angle=
1.8 degrees)
In this type of functioning, the following 8 binary sequence/code are used for rotation: (Considering step angle=
0.9degrees)
Program
Interfacing Diagram
Troubleshooting
If your motor is not rotating OR vibrating but not rotating, then you must check the following checklist:
1. First check the circuit connections and code.
2. If the circuit and code is ok, then check that the stepper motor gets proper supply voltage (generally 12v),
otherwise it just vibrate but not rotate.
3. If supply is fine, then check the four coil end points which in connected to ULN2003A. First find the two common
end points and connect them to 12v, then connect the remaining four wires to ULN2003A and try every possible
combination until motor get started. If you wouldn’t connect them in proper order then the motor just vibrate
instead of rotating.
The main purpose of DC interfacing with 8051 microcontroller is for controlling the speed of the motor. The DC
motor is an electrical machine with a rotating part termed as a rotor which has to be controlled. For example, consider
the DC motor whose speed or direction of rotation of DC motor can be controlled using programming techniques
which can be achieved by interfacing with 8051 microcontroller. So, in this article let us discuss about interfacing
DC motor with 8051 microcontroller.
Motor Driver IC used for Interfacing DC motor with 8051
Here, interfacing 8051 with DC motor requires a motor driver. There are various types of driver ICs among which
L293D is typically used for interfacing DC motor with 8051. L293 is an IC with 16 pins which are represented in
the figure below.
This describes a bidirectional DC motor that changes its direction automatically after a preset amount of
time (around 1S). AT89S51 is the microcontroller used here and L293 forms the motor driver. Circuit diagram is
shown above
In the circuit components R1, S1 and C3 forms a debouncing reset circuitry. C1, C2 and X1 are related to the
oscillator. Port pins P1.0 and P1.1 are connected to the corresponding input pins of the L293 motor driver. The motor
is connected across output pins 3 and 6 of the L293. The software is so written that the logic combinations of P1.0
and P1.1 controls the direction of the motor. Initially when power is switched ON, P1.0 will be high and P1.1 will
be low. This condition is maintained for a preset amount of time (around 1S) and for this time the motor will be
running in the clockwise direction (refer the function table of L293). Then the logic of P1.0 and P1.1 are swapped
and this condition is also maintained for the same duration . This makes the motor to run in the anti clockwise
direction for the same duration and the entire cycle is repeated.
Progr am.
ORG 00H // initial starting address
MAIN: MOV P1,#00000001B // motor runs clockwise
ACALL DELAY // calls the 1S DELAY
MOV P1,#00000010B // motor runs anti clockwise
ACALL DELAY // calls the 1S DELAY
SJMP MAIN // jumps to label MAIN for repaeting the cycle
DELAY: MOV R4,#0FH
WAIT1: MOV R3,#00H
WAIT2: MOV R2,#00H
WAIT3: DJNZ R2,WAIT3
DJNZ R3,WAIT2
DJNZ R4,WAIT1
RET
END
Notes.
The maximum current capacity of L293 is 600mA/channel. So do not use a motor that consumes more than that.
The supply voltage range of L293 is between 4.5 and 36V DC. So you can use a motor falling in that range.
Saneesh Cleatus Thundiyil
BMS Institute of Technology, Bangalore – 64 95
Microcontrollers 4 Sem ECE