0% found this document useful (0 votes)
27 views201 pages

ESD Book

Uploaded by

Samuel abhishek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views201 pages

ESD Book

Uploaded by

Samuel abhishek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 201

EMBEDDED SYSTEM USING 8051

A practical Approach

By

ETI Labs Pvt. Ltd


TABLE OF CONTENTS

Chapter 1 INTRODUCTION TO EMBEDDED SYSTEMS 1-4

1.1 Need of Embedded Systems 2


1.2 Characteristics of an Embedded System 2
3
1.3 Embedded System versus General Purpose System 4
1.4 Applications of Embedded system

Chapter 2 Components of Embedded systems 5-25

2.1 Central Processing Unit (CPU) 5


2.1.1 Microprocessor
2.1.2 Microcontroller
2.1.3 Coprocessor
2.1.4 SoC

2.2 Memory 10

2.2.1 Primary Memory


2.2.2 Secondary Memory
2.3 Interfaces 14
2.3.1 Digital Interfaces
2.3.2 Analog Interfaces

2.4 Input-output devices 17

2.4.1 Input devices and Sensors


2.4.2 Output devices and Actuators
2.5 Custom hardware 18

2.5.1 Field programmable gate array (FPGA)


2.5.2 Application specific Integrated circuit (ASIC)
2.5.3 FPGA and ASIC Comparison
2.6 Other Hardware 19
2.7 Software 22
2.8 Selection criteria for Embedded systems development 23
2.8.1 Individual Components Selection Criteria
2.8.2 Overall Criteria for selecting components

i
Chapter 3 8051 Microcontroller 26-33
3.1 Introduction 26
3.1.1 8051 Microcontroller Packaging
3.2 8051 Microcontroller Architecture
26
3.2.1 Schematic and Features
3.2.2 8051 Pin Diagram & Description
3.2.3 8051 System Clock
3.2.4 8051 Reset Circuit
3.3 8051 Memory Organization
31
3.3.1 Program memory organization
3.3.2 Data memory organization

Chapter 4 Embedded System Development (ESD) board 34-42

4.1 Introduction 34
4.2 Features: 35
4.2.1 W78E052D
4.3 Instructions to use ESD board 37

4.3.1 Procedure to Use Keil IDE:


4.3.2 Programming ESD using Nuvoton
Chapter 5 Getting started with ESD board 43-50

5.1 LED interfacing & programming 43


5.2 Pushbutton interfacing & programming 49

Chapter 6 Sensor Interfacing & programming 51-56

6.1 Sensor 51
6.2 PIR sensor 52
6.3 LDR sensor 53
6.4 Touch sensor 54
6.5 Sound sensor 56

Chapter 7 Display interfacing & programming 57-70

7.1 Seven segment display 57


7.2 LCD 61

ii
Chapter 8 Keypad interfacing & programming 68-70

Chapter 9 Actuator interfacing & programming 71-86


9.1 Buzzer 71
9.2 Relay 72
9.3 DC motor 74
9.4 Stepper motor 78
9.5 DC Fan 86
Chapter 10 Timer/Counter & its programing 87-111

10.1 Timer 87

10.2 Counter 95

Chapter 11 Serial Communication 112-135

11.1 UART 112


11.2 UART Programming in 8051 115
11.3 Bluetooth Interfacing and programming 125
11.4 GSM interfacing & programming 117

11.5 GPS interfacing & programming 132

Chapter 12 Interrupt 136-146

12.1 8051 interrupt 136

12.1.1 Timer interrupt 137


12.1.2 External hardware interrupt 139
12.1.3 Serial interrupt 141

12.2 Interrupt priority 145

CHAPTER 13 ADC and DAC Interfacing with 8051 147-168

13.1 ADC interfacing & programming 147


13.2 Analog Sensor Interfacing with 8051 158
13.3 DAC interfacing with 8051 166

CHAPTER 14 External Data Memory Interfacing with 8051 169-171

CHAPTER 15 RTC interfacing & programing 172-186

CHAPTER 16 Extending ports using 8255 PPI 187-197

iii
CHAPTER 1
INTRODUCTION TO EMBEDDED SYSTEMS
A system is an arrangement in which all its unit assemble work together according to a set of rules.
It can also be defined as a way of working, organizing or doing one or many tasks according to a
fixed plan. An embedded system, as its name suggests can be thought of as a computer hardware
system having software embedded in it. Embedded system is a combination of hardware and
programmable software which is specially designed for a particular task. It involves hardware
(microprocessor, microcontroller or SoC) and software (the executable code). It can be an
independent system or part of a large system. For example, a mouse or a keyboard is a small
embedded system that contributes to large computer system. Figure 1.1 is the block diagram of
embedded system.
Some real-life examples of embedded systems may involve ticketing machines, security systems,
lights and temperature controlling unit etc. Microcontrollers are nothing without a program in it.

Fig 1.1 Block diagram of an embedded system

Embedded System is an arrangement in which all units assemble and work together according to
a program or plan. Basic components of Embedded system are:

Processor, Memory, Sensor, Actuators, interfaces, display, software and power supply

1
1.1 Need of Embedded Systems
Any task can be done by specific discrete electronic components but using controller has some
advantages:

• Programmable: It is easier to change the code rather than changing the circuit which
makes it flexible and easy to maintain and troubleshoot.
• Less cost: Using discrete components and combining them to make complex circuit is
costlier than using single controller IC and some supporting hardware. Although some
small circuits using discrete components may be less costly than controller IC.
• Size: Using a single IC saves board space and reduce the size of the system.
• Reliable: There are very less chances of internal connection failure in controller IC because
internal connections are checked at the time of manufacturing the chip. Making
connections using discrete components has more chances of failure.

1.2 Characteristics of an Embedded System


• Single-functioned − An embedded system usually performs a specialized operation and
does the same repeatedly. For example: A pager always functions as a pager.
• Tightly constrained − All computing systems have constraints on design metrics, but
those on an embedded system can be especially tight. Efficiency is of paramount
importance for embedded systems. They are optimized for energy, code size, execution
time, weight & dimensions, and cost. It must be of a size to fit on a single chip, must
perform fast enough to process data in real time and consume minimum power to extend
battery life.
• Real time − Embedded systems are typically designed to meet real time constraints; a real
time system reacts to stimuli from the controlled object/ operator within the time interval
dictated by the environment. For real time systems, right answers arriving too late (or even
too early) are wrong.
• Reactive- Embedded systems often interact (sense, manipulate & communicate) with
external world through sensors and actuators and hence are typically reactive systems; a
reactive system is in continual interaction with the environment and executes at a pace
determined by that environment.
• Microprocessors based − It must be microprocessor or microcontroller based.
• Memory − It must have a memory, as its software usually embeds in ROM. It does not
need any secondary memories in the computer.
• Connected − It must have connected peripherals to connect input and output devices.
• HW-SW systems − Software is used for more features and flexibility. Hardware is used
for performance and security.

2
1.3 Embedded System versus General Purpose System
Embedded systems and general purpose uses similar components but there are several differences
in terms of hardware, software and their use.

• Purpose: Embedded systems are used for specific purposes. For example, a fire alarm
system continuously monitors a place for fire and alarms using buzzer/speaker and can
sends notification to concerned authority. While general purpose system can be used for
many number of applications simultaneously or can be reconfigured for new purposes. For
example, a computer can be used for developing applications, playing games, listening
songs etc.
• Resources: Embedded systems have limited hardware and software resources which are
sufficient for their purpose. General purpose systems have large number of resources which
may not be used at the same time and can be increased or decreased. For example, data
memory in embedded systems is limited to its specific task but in general purpose systems,
amount of memory can be changed depending on the requirement or may remained empty
depending on the number of concurrent tasks.
• Operating system (OS): Embedded systems focus on deadlines and reliability of the tasks.
A failed task could lead to system failure. General purpose systems focus on resource
management, memory management and scheduling of the tasks. A task failure will not be
a system failure. So, OS is needed in general purpose system but embedded systems either
do not require OS or have small/scaled down version of OS.
• Hardware interaction: A program written for embedded system directly interacts with
the hardware through registers but in general purpose system, program generally uses APIs
to interact with hardware, that comply with the OS.
• Software applications: In embedded systems, application programs are fixed and are
modified rarely after production. In general purpose systems, applications programs are
added, updated and removed frequently.
• System updates: As in embedded systems, hardware and software are rarely updated after
production, so a system cannot be modified while general purpose systems are frequently
updated through software patches and physically changing the hardware. As a
consequence, removing the faults in embedded systems is difficult process as compared to
general purpose systems after production.
• Firmware: The user code written for embedded system is stored in Flash/ROM and
directly executed when powered-on and is known as firmware. The firmware code in
general purpose system is used as bootloader and for checking hardware functionality and
is directly executed when powered-on. This firmware code then loads the OS which in turn
loads the user codes to be executed.
• Primary memory: In embedded systems, user code is generally stored and executed from
Flash memory and sometimes from RAM. Temporary data is stored in RAM in embedded
systems. In general purpose systems, bootloader is stored and executed from Flash

3
memory. Temporary data is stored in RAM and OS processes, and user codes are copied
from secondary memory to RAM for execution in general purpose systems.
• Secondary memory: Small amount of secondary memory is used in embedded systems
for storing non-volatile data and large amount of secondary memories are used for storing
user and system files in general purpose embedded systems.

1.4 Applications of Embedded system


The World is filled with Embedded Systems. The development of Microcontroller has paved
path for several Embedded System application and they play a significant role (and will continue
to play in the future as well) in our modern day life in one way or the other.
Starting from consumer electronics like Digital Cameras, DVD Players to high end and advanced
systems like Flight Controllers and Missile Guidance Systems, embedded systems are
omnipresent and became an important part of our life.
Embedded systems have applications in almost every field. Some of the common applications with
examples are listed below:
• Security – Burglar alarm, CCTV video recording
• Medical – Monitoring patient’s blood pressure, heart rate and alerting someone if not
normal
• Home automation and power saving – Automatic controlling of electrical appliances based
on temperature and light intensity, water level controller
• Agriculture – Measuring and maintaining soil moisture
• UAV – Balancing helicopters
• Mobile – Automatic screen brightness, making call
• Safety – Fire detection and control
• Robotics – Path follower
• Environment – Measuring particle pollution
• Automobile – Driverless car
• Consumer electronics – Set-top box, Refrigerator, Microwave Oven
• e-Payment – Card swipe machine

4
CHAPTER 2
COMPONENTS OF EMBEDDED SYSTEMS
Embedded system consists of various hardware and software components. Common hardware
components include CPU, memory, Input-Output devices, communication interfaces, sensors,
actuators etc. and software includes application program and Real-Time Operating System
(RTOS). Sometimes Field Programmable Gate Array (FPGA), Application Specific Integrated
Circuit (ASIC) are used in embedded systems.

2.1 Central Processing Unit (CPU)


CPU is an electronic circuit which interacts with all the components. It takes data from input
devices, process them and converts into information, give the commands and data to output devices
according to program (set of instructions) stored in the memory. It consists of controller and
datapath circuits. Controller in CPU is commonly known as control unit and the hardware other
than control unit is called datapath. There are three major components of CPU: Arithmetic Logic
Unit, Memory, and Control Unit as shown in Figure .

External AD Bus pins


Internal AD Bus

Address/Data
Register
R0 Accumulator
General Purpose Registers

R1 ALU
Temporary Flags
R2 Register

• PC/IP
• PCS/Link
Rn

Instruction
IR
Decoder
To various parts
Control Signals

To various parts
Power Pins

Power
Read/Write Pins
Memory & I/O

and Timing and Control unit


Clock

Clock Pins

Figure 2.1 CPU Block Diagram

5
Arithmetic Logic Unit (ALU)
ALU consists of hardware, for all the arithmetic and logic operations of the CPU like addition,
subtraction, logical AND etc. It has all the hardware required for arithmetic and logical operations.
It takes operands as input, select signals for selecting the specific operation and gives results as
output. The select lines are decoded from op-code of the currently executing instruction. They are
used to select the operation to be performed by specific hardware like adder for addition. ALU has
buffer registers for temporary storing the inputs and outputs. The number of inputs and outputs
depends on the type of operation. For example, an adder takes two operands and a carry as input
and gives sum and carry as output. A logical NOT operation takes one operand as input and gives
inverted input as output.
Memory
CPU has small amount of memory, commonly known as registers, for storing data. Registers can
be used for general purpose storage or special purpose. Common special purpose registers are
Accumulator, Temporary Register, Program Counter (PC), Program Counter Storage (PCS) or
Link Register, Instruction register (IR), Status Register, Address/Data (A/D) register. In some
CPUs, Accumulator and Temporary Register are directly connected to the ALU and serve as
operands. Some CPUs do not have these registers and any general purpose can be used as operands.
PC is used for storing the address of the next instruction to be executed. In other words, it keeps
track of the program execution. The PC value is changed, when program execution needs to be
changed and old value is copied to PCS/Link register. When program execution needs to be
returned, PCS value is copied back to PC. Some CPUs use stack memory instead of PCS for
temporary storage of the PC value. IR register is used to store the currently executing instruction
fetched from the program memory. It is decoded by instruction decoder & control unit and control
signals are generated by control unit. Status register is used to store the status of the CPU and the
last instruction executed. It has several flags which store different status information. For example,
carry flag is used to store the status of carry generated in addition operation. A/D register is used
to store address and data from/to the memory. It may have memory management unit (MMU) for
translating the logical addresses generated by CPU to physical RAM addresses, for memory
protection from user applications. Simpler CPUs usually do not require MMU.
Control Unit (CU)
CU is responsible for controlling all the operations of the CPU. It gives control signals to all the
data path components for executing the instructions. The instructions are further divided into
smaller instructions known as micro-instructions and the operation performed by one micro-
instruction is known as micro-operation. One micro-instruction takes one clock cycle for
completing its micro-operation. The CU can be hardwired or microprogrammed. Hardwired CU
has dedicated circuit for generating the control signals for every micro-instruction.
Microprogrammed CU has memory and decoding circuit for generating the control signals.
In addition to the above-mentioned components, CPU has power control and clock control
circuitry. Power control circuit is used for providing adequate power to all the components of the

6
CPU for their safe and reliable operation. Clock control circuit provides clock with necessary
frequency to all the sequential components of the CPU. The clock frequency limits depend on the
speed of the hardware components.
Instruction-Set
Instructions are the commands given to the CPU. They are stored in permanent memory and may
be executed from volatile or permanent memory. Instructions consists of OPCODE and the
operands. OPCODE specifies the operation to be performed by the instruction on the operands.
Every instruction is executed in three steps: Fetch, Decode and Execute. Decode can be combined
with Execute. Fetch is process of fetching the instruction from program memory and store in
internal instruction register of the CPU. Decode is the process of obtaining a set of signals from
the OPCODE, to be used for the execution of the instruction. Execute is actual execution of the
instruction, which is controlled by the signals generated by the CU in synchronization with the
system clock. Instruction-set is the set of instructions available for a particular CPU. Different
instructions have different formats which depends on the architecture of CPU and the operation to
be performed by the instruction.
Single-operand instructions: These types of instructions have only one input and same operand is
used for output. The format for single operand is “OPCODE operand”. For example, logical NOT
instruction can be written as “NOT R1”, where R1 is the operand and result is also stored in R1.
Two-operand instructions: These types of instructions have two inputs and one of the input
operand is also used for output. The format for two-operand is “OPCODE operand1 operand2”.
For example, Addition instruction can be written as “ADD R1,R2”, where R1 and R2 are added
and result is also stored in R1.
Three operand instructions: These types of instructions have two inputs and one output. The format
for single operand is OPCODE operand1 operand2 operand3. For example, Addition instruction
can be written as “ADD R1,R2,R3”, where R2 and R3 are added and result is also stored in R1.
The CPU can perform different operations as specified by the instructions. Depending on the type
of operation, instructions can be divided into different categories:
Data Transfer: Data transfer instructions are used to transfer data between CPU Registers and
Memory. For example, “MOV R1,R2” copies data from R2 to R1.
Arithmetic: Arithmetic instructions are used to perform arithmetic operations by the ALU. The
operand can be register, memory location or immediate data given with the instruction. For
example, “ADD R1,R2” adds data from R1 and R2 and put the result in R1.
Logical: Logical instructions are used to perform logical operations by the ALU. The operand can
be register, memory location or immediate data given with the instruction. For example, “AND
R1,R2” logically AND bitwise data from R1 and R2 and put the result in R1.

7
Branching: Branching instructions are used for controlling the execution sequence of the
instructions. For example, “JMP #11110000” is used to transfer execution to address 11110000.
Co-processor Instructions: Co-processor instructions are used to give instructions and/or data to
another processor working with the CPU.
Other: Other type of instruction include system instructions like software interrupts, power down
instructions etc.
There are different ways, the operands are provided with the instructions. The way of specifying
the operand is called addressing mode. There are five types of addressing modes:
Immediate mode: In this mode, the operand is provided in the instruction. For example, in
instruction ADD A,#11110000B the second operand ‘11110000’ in binary is provided in the
instruction with a ‘#’ symbol.
Register mode: In this mode, the operand is in a CPU register and register is specified in the
instruction. For example, in instruction ADD A,R1 the second operand is in CPU register R1.
Direct mode: In this mode, the operand is in a memory and memory address is provided in the
instruction. For example, in instruction ADD A,10101010B the second operand is at memory
location ‘10101010’.
Register Indirect mode: In this mode, the operand is in a memory with memory address in a CPU
register and register is specified in the instruction. For example, in instruction ADD A,@R1 the
second operand is at memory location, contained in CPU register R1.
Implicit mode: In this mode, the operand is implicit and need not to be provided by the instruction.
For example, in instruction ADD A,@R1 the second operand is at memory location, contained in
CPU register R1.
There are two types of common Instruction Set Architectures: RISC (Reduced instruction set
computer) and CISC (Complex instruction set computer). Earlier, processors with RISC
architecture were having less number of instructions as compared to processors with CISC
architecture. But now RISC architecture are also implemented with many number of instructions.
So, RISC may have more number of instructions than CISC architecture. In CISC, instructions are
complex i.e. single instruction can perform a complex function. For example, "DJNZ reg/mem,
addr" (decrease and jump if not zero) instruction in 8051 micro-controller decreases the value in
register "reg" or memory location "mem" by 1 and then check if it is equal to zero. If the value is
not zero, it jumps to given address. Examples of processors using CISC architecture: 8085, x86,
x64 processors from Intel, 8051 from Atmel etc. In RISC, instructions are simple i.e. single
instruction can perform a simple (generally single) function. For example, in AVR micro-
controller "DEC reg" (decrease reg by 1) and "BRNE k" (jump to specified adddress). One
instruction is performing one operation. So, two instructions are needed for performing the same
operation in AVR. Examples of processors using RISC architecture: AVR from Atmel, PIC from

8
Microchip, ARM etc. Many processors do not use pure RISC architecture to make instruction set
more powerful. For example, ARM provides conditional execution of the many instructions. Inline
barrel shifter is used to shift/rotate the operand before it is used by the instruction.
2.1.1 Microprocessor
When all the functionality of the CPU is implemented on single chip, it is known as
microprocessor. A microprocessor still needs to connect to the memory and input-output devices
as shown in Figure 2.1. It reduces the power consumption, increases efficiency and reduces cost
per unit as they can be manufactured with fully automated process with high volumes. Single-chip
CPUs increase reliability as there are fewer electrical connections which can fail. Microprocessors
may have multiple cores which acts like multiple CPUs on a chip with shared external memory
and peripherals. They are generally used in general purpose systems for high performance
applications.
Address/Data Bus

Microprocessor Communication Other


(CPU) Memory I/O Ports Timers
Interfaces peripherals

Control Signals

Figure 2.1 Microprocessor with peripherals

2.1.2 Miocontroller
Microcontroller is a combination of CPU and peripherals on single chip. Peripherals include
memory, input-output ports, timers, communication interfaces, ADC, DAC etc. as shown in Figure
2.2. Microcontrollers may have more than one core but they are not common. Microcontrollers
have fixed amount of memory and peripherals. They are made to work on low speeds and low
power applications as compared to microprocessor. They are generally used in embedded systems.
Microcontrollers can support floating point and DSP operations for high performance applications.

Communication
Memory Timers
Interfaces
CPU
I/O Ports Other peripherals

Figure 2.2 Microcontroller

9
2.1.3 Coprocessor
A coprocessor is a processor which works with primary processor (CPU) adding some extra
functionality. Coprocessor can perform floating point arithmetic, graphics processing, signal
processing, encryption or any special operation. The coprocessor which performs floating point
arithmetic operations are known as FPU (floating point unit) and the coprocessor which performs
graphics operation are known as GPU (graphics processing unit). Coprocessors accelerate system
performance by taking the special load from the main processor and so helps in customizing the
system. Users who do not need high performance need not pay for coprocessor.
2.1.4 SOC
System on chip (SoC or SOC) is an integrated circuit that integrates all components of a computer
or other electronic systems. The on-chip peripherals can be input-output ports, timers,
communication interfaces etc. and some advanced peripherals like Graphics Processing Unit
(GPU), Wi-Fi module, Coprocessor etc as shown in Figure 2.3.
In general, there are three distinguishable types of SoCs. SoCs built around a microcontroller,
SoCs built around a microprocessor (this type can be found in mobile phones), and specialized
SoCs designed for specific applications which is Programmable SoC (PSoC), where some of the
internal elements are not predefined and can be programmable in a manner analogous to a field-
programmable gate array (FPGA) or a complex programmable logic device (CPLD). A PSOC has
CPU, configurable analog and digital peripherals and programmable interconnections.

Memory Communication
CPU Timers
(optional) Interfaces

Display Wireless
GPU I/O Ports
Interface communication

Floating point Multimedia Other


Coprocessor Processing peripherals

Figure 2.3 SOC Block Diagram

2.2 Memory
Memory is an electronic circuit which is used to store information. Memory can be either volatile
or non-volatile. Volatile memory loses content when powered-off. Non-volatile memory keeps the
content even when powered-off. There are two types of memory used in embedded system.
Memory can be present on-chip or off-chip. Memory signals include data, address (ADDR), chip
enable (CE), output enable (OE) and write enable (WE) as shown in Figure 2.4. Every m-bit data
is stored at a location specified by the n-bit address lines. CE is used enable the memory chip. OE
is used to read the data from memory specified by ADDR and WE is used to write the data at
location specified by ADDR.

10
n
Address
CE Memory m
Data
OE 2n:m
WE

Figure 2.4 Memory Block Diagram

2.2.1 Primary Memory


Primary memory is the main memory of the embedded system which is used to store program and
data. Primary memory is directly connected to address and data lines of the CPU as shown in Figure
2.5. When the CPU is powered-on, it starts executing the code from one of the primary memory
and the code is known as firmware. The primary memory can be volatile or non-volatile. Different
types of primary memories are available for different purposes. CPUs have multiplexed address
and data lines to have number of pins. To interface primary memory with the CPU, address/data
needs to be demultiplexed via address latch and higher unused address lines needs to be decoded
to generate CE signal. OE and WE are directly connected to CPU’s RD and WR signals
respectively.

Address n
AD Bus Latch Address m

CPU
Address
Decoder
CE Memory
Data
RD OE 2n:m
WR WE

Figure 2.5 Primary Memory Interfacing

NOR Flash memory


It is non-volatile solid-state memory, generally used to store and execute program and sometimes
to store data. It is made with FGMOS transistor which resembles MOSFET but with an addition
of floating gate which is used to store charges as shown in Figure 2.6. One cell stores 1-bit of
information and read, write and erase operations are controlled by applying specific voltages on
Vs, Vg and Vd terminals. Normally it behaves like a MOSFET and conducts when Vg is greater
than threshold value of the transistor and treated as Logic1. When charge is stored in floating gate,
its threshold voltage increases and current conduction reduces to less than 50% and is treated as
Logic0.
Vs Vg Vd

Control Gate
SiO2

Floating Gate
SiO2

N+ N+

P-substrate

Figure 2.6 FGMOS Transistor Cell

11
In NOR flash memory, transistors are connected in NOR gate like structure as shown in Figure 2.7
and single bit at a time can be operated at a time. Vg is connected to decoded address (WLn) and
Vd is connected to bit line which is the data for the memory.
Bit Line

WL0 WL1 WL2 WL3 WL4 WL5 WL6 WL7

Figure 2.7 NOR Flash Structure

Random access memory (RAM)


It is volatile memory and used to store temporary data. Sometimes, RAM is also used to execute
the program. To execute the program from RAM, it has to be copied from a non-volatile memory
to RAM. RAM can be either static (SRAM) or dynamic (DRAM). The basic unit for storing 1-bit
of information in dynamic RAM is shown in Figure 2.8. A capacitor is used to store charge which
is treated as Logic1. The read and write operation is controlled by MOSFET with gate connected
to decoded address (WL) and drain connected to bit line which is the data for the memory.
WL

Bit Line

Figure 2.8 Dynamic RAM Cell

Cache memory
The basic unit for storing charges in static RAM is Flip-flop as shown in Figure 2.9. Static RAM
are faster and costlier than dynamic RAM and take more semiconductor area in manufacturing.
The clock (CLK) is used as the write signal. Whenever a clock edge occurs at the CLK terminal,
data present at D terminal is stored in the flip-flop. Q terminal is used to read data from the
memory.

Table 0-1 SRAM Truth Table

CLK D Qn Qn+1
No transition x x Qn
Transition occurs 0 x 0
Transition occurs 1 x 1

12
D Q

CLK

Figure 2.9 Static RAM Cell

Cache memory is a static RAM placed close to the CPU. They are generally used to store copy of
frequently used data from the DRAM, so increasing the performance of the system.
2.2.2 Secondary Memory
Secondary memory is auxiliary memory and used to store permanent and large amount of data. It
is connected to CPU via interface chip in microprocessor as shown in Figure 2.10. The
microcontroller and SOC have on-chip interface for memories Secondary memories are always
non-volatile. Primary memories are always faster and costlier than secondary memories Different
types of secondary memory are available for different purposes.

Interface
AD Bus
signals
Interface
CPU RD
Chip

WR
Memory
2n:m

Figure 2.10 Secondary Memory Interfacing

NAND Flash memory (EEPROM)


It is non-volatile solid-state memory, generally used to store data. It is frequently used in embedded
systems for storing small amount of permanent data and as memory cards. In general purpose
system, it is used in the form of Solid State Drives (SSD) and USB flash drives. NAND flash uses
the same cell as NOR flash for storing 1-bit data but structure of the NAND flash resembles NAND
gate. FGMOS transistors are connected in series and data can be read or written as blocks only.
Bit Line

Bit Line
Ground WL0 WL1 WL2 WL3 WL4 WL5 WL6 WL7 Select
Select

Figure 2.11 NAND Flash Structure

13
Other secondary memories
Other types of secondary memories include hard disk drive (HDD), optical drives, magnetic tapes
etc. which are rarely used in embedded systems.

2.3 Interfaces
Interfaces are used by CPU to communicate with memories, sensors, actuators and input-output
(I/O) devices. Microprocessor provides interfacing through its address and data lines. Primary
memories are directly interfaced through address and data lines. I/O devices with parallel data can
also be interfaced through address and data lines. Microprocessors provide two ways to interface
I/O devices: memory mapped I/O devices and I/O mapped I/O devices. Memory mapped I/O
devices are interfaced and accessed same as primary memories. I/O mapped I/O devices are also
interfaced similar to memory mapped I/O devices but different instructions are used to access
them. Secondary memories, sensors, actuators and other I/O devices are interfaced with the
microprocessor through peripherals like I/O ports, communication protocol chips etc. which are
connected to address and data lines of the CPU either as memory mapped or I/O mapped I/O. In
microcontrollers and SOCs, many memory mapped peripherals are provided on the chip and their
input-output pins provide many types of interfaces for external world.
2.3.2 Digital interfaces
Digital interfaces work on discrete voltage levels. There are two logic levels, Logic0 and Logic1,
which corresponds to two different values of voltage as shown in Figure 2.12. General purpose
input-output (GPIO) are used to transfer 1-bit digital data. Digital interfaces are used widely to
communicate with sensors, wireless communication modules, many I/O devices like LCD, LED,
push button etc. They are further divided into serial and parallel interfaces.
Amplitude
Logic 1

Logic 0
Time

Figure 2.12 Digital Signal

Parallel interfaces: This interface is used transfer more than one-bit at a time. Group of GPIO pins,
known as I/O ports, are used for transferring data parallelly. I/O ports can transfer data in group of
n-bits (n=8/16/32/64…) bits at a time. Parallel interfaces require ‘n’ data lines and control lines, if
any used by the protocol as shown in Figure 2.13. They are easily implemented than serial
interfaces. They are used in internal connections of the ICs.

14
Data n

Device
Control Signals
CPU with
Status Signals
Parallel Interface
Handshaking
Signals

Figure 2.13 Parallel Interface

Serial interfaces: These types of interfaces transfer 1-bit at a time. There are several types of
standard protocols for serial interfaces like SPI, I2C, UART etc. They use fewer data lines than
parallel interfaces but communication speed is slower and uses complex hardware. GPIOs can also
be used for serial communication using bit-banging (transmitting/receiving individual bits by
software). In this way, there is no need of standard protocol hardware but software program
becomes complex. Serial protocols are further divided into synchronous and asynchronous
communication protocols.
Synchronous communication: This type of serial communication requires clock for
synchronization between transmitter and receiver as shown in Figure 2.14. The clock is generated
by master and decides the speed of the communication. Commonly used synchronous protocol in
embedded systems are serial peripheral interface (SPI), Inter-integrated circuit (I2C) etc.

Device
Data
with
CPU
Clock Serial Interface
(Synchronous)

Clock

Data

Figure 2.14 Serial Interface (Synchronous)

Asynchronous communication: This type of serial communication does not require clock for
synchronization. The clock is generated by transmitter and receiver locally. The clock frequency
can be different for transmitter and receiver but communication speed should be agreed in advance.
Transmitter (Tx) and receiver (Rx) are cross connected between two devices as shown in Figure
2.15. Widely used asynchronous protocol in embedded systems is universal asynchronous receiver
transmitter (UART).

15
Device
Tx Rx with
CPU Rx Tx Serial Interface
(Asynchronous)

Tx

Rx

Figure 2.15 Serial Interface (Asynchronous)

2.3.3 Analog interfaces


Although CPUs can process digital data, in many embedded systems, the CPU needs to
interface with the non-digital components i.e. analog. All the processes in the environment
gives analog readings as shown in Figure 2.16, which are converted into digital data using
analog to digital converter (ADC) before processed by the CPU. For example, a
microphone gives analog voltage corresponding to audio level, which is then converted to
digital data using ADC, and read by the CPU.
Amplitude

Time

Figure 2.16 Analog Signal Figure 2.17 ADC Block Diagram

The various steps involved in the analog to digital conversion are sampling, holding,
quantization and encoding as shown in Figure 2.18. Sampling is used to take the samples
from the analog signals and hold for the time of converting. The signal value is quantized
to fix levels which defines the resolution of the ADC. Quantized value is then encoded to
predefined binary values which can be processed by the CPU.

Figure 2.18 ADC Process Steps

16
Similarly, digital data from CPU is converted into analog voltage to be used by analog
devices as shown in Figure 2.20. Vout is the analog voltage, which is
voltage across the feedback resistor R and is converted by weighted sum of the currents
generated by the bits of the binary data from CPU. For example, DAC converts digital data
of a song to analog voltage which is fed to the speaker circuit for playing the song.

Figure 2.19 DAC Block Diagram Figure 2.20 ADC Process

2.4 Input-Output Devices


Input and output devices are used by CPUs to connect to outside world by moving data in and out
of the system. CPUs in the embedded systems, are usually not interfaced with external world like
general purpose system with keyboard, mouse, Graphic User Interface (GUI) etc. They are
interfaced with devices such as sensors, actuators and communication modules using various
interfaces discussed in section 2.3.
2.4.1 Input devices and Sensors
Input devices are the components which takes some input from the external environment and gives
the data to the processing unit. In case of general purpose computer, input devices are keyboard,
mouse etc. whereas in case of embedded system the input devices are generally application specific
sensors.
Sensor is a type of transducer which converts one form of energy into electrical energy. Sensor
take specific input from physical environment which could be light, heat, motion, moisture,
pressure, or any environmental phenomena and gives the output as an electrical signal.
2.4.2 Output devices and Actuators
Output devices are the components which takes the processed data or information from the
processing unit and present it to the other device or user in any form. In case of general purpose
computer, output devices are Printer, monitor etc. whereas in case of embedded system the input
devices are generally application specific actuators or displays.
An actuator is also a kind of transducer which converts any form of energy into motion. It also can
be used to apply a force. An actuator typically is a mechanical device that takes energy usually
energy that is created by air, electricity or liquid — and converts it into some kind of motion. That
motion can be in virtually any form, such as blocking, clamping or ejecting. Actuators typically
are used in manufacturing or industrial applications and might be used in devices such as motors,
pumps, switches and valves.

17
2.5 Custom Hardware
To design an electronic system, a multitude of technically valid solutions using a combinations of
off-the-shelf chips, including programmable components (µC, µP), analog components,
programmable logic (FPGA, CPLD) and memories may be required.
Sometimes it is required to integrate just the functionalities you need in a chip dedicated to your
application (or a limited sub-class of applications) and that is what an ASIC is: a combination of
analog functions, digital functions, programmable logic, programmable controllers, and different
types of memory, in a single chip. There are two ways to design custom hardware: ASIC and
FPGA.
2.5.1 Field programmable gate array (FPGA)
FPGAs are the ICs, designed such that their hardware can be configured by the user after
manufacturing in the field. They are configured by programming the hardware using Hardware
Description Language (HDL). FPGAs consists of programmable logic blocks, I/O blocks and
interconnects, and some complex logics like adders, multipliers, memories etc. as shown in Figure
2.21. Logic blocks are used to implement any digital logic, I/O blocks contain drivers for I/O pins.
Routing between logic blocks, I/O blocks and complex logics is programmable. In embedded
systems, FPGAs are not frequently used.

Figure 2.21 FPGA Block Diagram

2.5.2 Application specific Integrated circuit (ASIC)


ASICs are customized ICs manufactured for a specific purpose. For example, a chip can be
designed for recording voice. They are also designed using HDL. They are implemented in many
ways such as standard cell design, gate array design, full custom design and structured design. Due
to non-compatible tools by different manufactures and third-party, manufacturers create their
functional blocks with known electrical characteristics like delay, capacitance etc. and make them
available to all the tools. In gate array design, manufacturer predefines the active devices like
transistors and kept the wafer containing these devices in stock. Designing using gate array, only
interconnections have to be made in metal layers. Gate array design is also known as semi-custom
design. In full custom design, everything has to be designed. Structured design is like gate array
design, except that some metal layers are predefined.

18
2.5.3 FPGA and ASIC Comparison
FPGA design cycle include steps: Specifications, HDL, simulations, Synthesis, Place and Route,
dump code onto FPGA and Verify. While designing using ASIC, floor planning and advanced
verification have to be done for manufacturing. The FPGA design flow eliminates the complex
and time-consuming floor planning, place and route, timing analysis, and mask stages of the
project since the design logic is already synthesized to be placed onto an already verified FPGA
device.
1. Speed: ASIC are always faster than FPGA as they are designed for a specific application
and can be optimized according to needs.
2. Cost: For small applications, It is better to design and test on an FPGA before implementing
on an ASIC. For complex and large volume, ASIC are always cheaper than FPGA. An
ASIC wastes very little material compared to an FPGA and the recurring costs are low.
3. Size/Area: FPGAs are manufactured for general purpose. FPGA contains lots of CLB,
IOB, and routing channels which are connected according to custom application. So, they
consume larger area than ASICs and there can be wastage of having unwanted circuitry.
4. Power Consumption: Due to unwanted circuitry in FPGA, it consumes more power than
ASIC.
5. Flexibility: An ASIC can no longer be altered after it gets out of the production line. That
is why the designers need to be totally sure of their design, especially when making large
quantities of the same ASIC. The programmable nature of an FPGA allows the
manufacturers to correct mistakes and to even send out patches or updates after the product
has been bought.
6. Re-Usability: A single FPGA can be used for various applications, by simply
reprogramming it (dumping new HDL code) whereas ASIC are application specific cannot
be reused.
7. Time to Market: As FPGAs are manufactured for general purpose and just need to be
configured as per the requirements. In contrast, ASIC needs to be manufactured as per the
requirements. So, time to market for FPGA based systems is less, compared to ASIC.

2.6 Other Hardware


In addition to hardware mentioned in above sections, there are some hardware which are essential
for embedded systems to work and there can be some application specific circuit which are used
with some specific devices or components.
Power supply: A power supply is a device that supplies electrical energy to electrical circuits. It
can be power source and/or electrical power converter. Power source generates electrical energy
by converting it from some other form of energy. For example, battery converts chemical energy
to electrical energy and is used to supply it to electrical circuits. The battery contains two
electrodes and one or two electrolytes as shown in Figure 2.22. The chemical reaction between

19
electrodes and electrolyte generates a potential difference between the electrodes. If the chemical
reaction in the battery can be reversed by the application of electric current, then the battery can
be recharged. There are two types batteries: Primary and Secondary. Primary battery’s chemical
reaction can’t be reversed, so they are non-rechargeable batteries. Secondary battery can be
recharged as their chemical reaction can be reversed.

+ -

Figure 2.22 Battery Structure and Symbol

Many times, some part of embedded circuits need different power than others or whole system
works on different power than the available. Electrical power converter converts one form of
electrical energy to another which can be used as needed by the circuits. DC-DC converter converts
one level of voltage to another, keeping the total power constant by corresponding changing the
input current level. Buck converters step-down the input voltage while boost converters step-up
the input voltage. Linear voltage regulators step-down the input voltage but not changing the input
current. A considerable amount of power is wasted as heat inside the linear voltage regulators if
difference between input and output voltage is high. DC-DC converters take more space and are
costlier than linear voltage regulator. DC-DC converters produce more ripples in the output in
conversion than linear voltage regulator. Linear voltage regulators are available as fixed voltage
output and adjustable voltage output. Application circuits for both type of regulators are shown in
Figure 2.23.

Adjustable
Fixed Voltage IN OUT
IN Voltage
Regulator OUT Regulator R1
GND ADJ
Vin Cin Vout
Cout
Vin Cin Vout
Cout

R2

Figure 2.23(a) Fixed Voltage Regulator (b) Adjustable Voltage Regulator

Another type of power supply converter is AC-DC converter as shown in Figure 2.24. This type of
converter uses transformer to step-down AC voltage, rectifier and filter to convert AC voltage to
DC voltage and then voltage regulator can be used to output desired voltage to the load.

20
AC input Transformer Rectifier Filter Regulator Load

Amplitude
Amplitude Amplitude Amplitude
DC output
Amplitude
Time
Time Time Time Time

Figure 2.24 AC to DC Converter

There are some other types of power supplies which are generally not the part of embedded systems
but are used at the time of development and testing of the system. Switched Mode Power Supply
(SMPS) are used to convert AC to DC with high accuracy and include safety features such as high-
current detection, short circuit protection etc. They are generally used in general purpose
computers. Programmable power supplies have configurable output parameters such as voltage,
frequency, current etc. They are highly used in generating waveforms for embedded systems
development and testing. Uninterruptible power supply (UPS) has two or more input sources. It is
powered from the AC and charges a battery simultaneously. If there is any failure in the AC supply,
power from the battery is instantly supplied to the load, so that there is no interruption.
Timing circuit: Embedded systems requirement CPU for programming which uses clock signal for
its operations to be synchronized. Some CPU chips include internal RC oscillator for generating
clock but for some high accuracy operations, an external oscillator is required. Some CPU chips
do not include internal oscillator which makes it compulsory to use external oscillator. Every CPU
chip comes with two clock pins. External clock can be provided on one of its pin and other pin can
be used for other purposes or an oscillator can be connected between the pins for generating the
clock signal as shown in Figure 2.25. Most used oscillator is crystal oscillator, which provides clock
with high accuracy.

Figure 2.25(a) Crystal Oscillator (b) External Clock

Reset circuit: Every CPU must be reset to start/restart its working. To reset a CPU, a pulse for a
specified time (provided in datasheet) must be given to its reset pin. This pulse can be active high
or active low. It can be generated by a RC circuit as shown in Figure 2.26, in which charging and
discharging of capacitor through resistor decides the time of the pulse. Proper values of resistor
and capacitor must be used to ensure reset of the CPU.

21
Figure 2.26 Reset Circuit (a) Active High (b) Active Low

2.7 Software
The most important part of the embedded systems is that they are programmable. Program makes
it easy to test, debug and change the embedded systems. There are two types of software used in
embedded systems: Application program and Real Time Operating System (RTOS). Most of the
embedded systems need application program only. RTOS is used in high-end complex applications
only.
2.7.1 Application program
Application program is the user program which is executed to perform any task. It is stored and
executed from NOR flash memory. Sometimes, it is executed from RAM. In most embedded
systems, it is executed as soon as the system is powered-on and known as firmware. Application
program is responsible for all the overall operation of the system. Application program in
embedded system is small, generally fit in few kilobytes of memory. In embedded systems,
application program is referred as embedded program.
2.7.2 RTOS (Real Time Operating System)
An embedded system can have more than one application software which are managed by OS.
Major functions of operating systems are memory management, resource management and
scheduling of application programs. OS handles multiple application programs, so there is
possibility of missing deadlines. In embedded systems deadline missing can leads to system
failure. RTOS is an operating system with special scheduling algorithm which focus on time
constraints. Its scheduling algorithm gives priority to the tasks whose deadline is early. An RTOS
may be either event-driven, time-sharing or both. Following are the properties of RTOS:
• Context switching time is very less.
• Inter-process communication is faster using pointers.
• It can interrupt background processes or pause some of its system processes.
• It can perform few tasks and reject new tasks, if resources are not available within
time limits.
• Kernel can boot and initialize the system, then load the scheduler and gets itself
dumped out of the memory.
• Only small and important library functions are available, as memory is limited in
embedded systems.
• Priority based pre-emptive scheduling is generally performed in RTOS.
• RTOS generally occupies few KBs of memory.

22
2.8 Selection criteria for Embedded systems development
The most important consideration for selecting the components for any embedded system
application is the application itself. Each embedded application comes with a specific set
of requirements.
2.8.1 Individual Components Selection Criteria
1. CPU: The selection of CPU is very critical for the embedded system. For general purpose and
high-performance applications, microprocessors are best suited. As they have low transistor
density compared to microcontroller and SOC, there is less heating problems in high
performance. Microcontrollers are used in specific purpose systems as they have on-chip but
limited resources and consume less space. SOCs are used in both general purpose and specific
purpose systems. For embedded systems, generally a microcontroller or an SOC is used based
upon the requirements of the application. The specifications for every chip is provided in
datasheet and its functionality and details are provided in reference manual of the chip.
Following features should be considered while selecting a CPU:
a. Speed: Speed of the CPU depends on clock frequency and architecture of the
CPU. Speed is important factor as embedded system are designed to
complete the tasks before deadlines. Speed is also important for
communication protocols.
b. Internal Memory: While selecting a CPU, its internal program and data
memory should be enough for application code, data and future firmware
upgrades.
c. Interfaces: Various interfaces are available in different types of CPU chips.
While choosing a CPU, type and number of interfacing ports should be such
that, it fulfils the requirements of the system and not wasting the resources
available. For example, I2C or analog interface is used for most of the
sensors. UART is used for most of the communication modules.
d. Power Consumption: It is an important factor especially in battery powered
applications. Power consumption should be as low as possible. CPU ICs
have different power consumption in different modes like normal mode,
standby mode, sleep mode etc.
e. Cost: The development cost for the system depends on the cost of CPU as
well as other components. Cost of the CPU should be as low as possible
while fulfilling all the system requirements.
f. Support: Software and hardware support are essential part of the
development process. The support can be provided by manufacturer,
distributer and third parties. Many of the manufacturers provide free

23
software like compiler, simulators etc. for non-commercial purposes.
Community support is another essential part of the development as it can
reduce the time to market. Online sample codes and libraries should also be
available.
g. Packaging: The same CPU can be provided in many packages by the
manufacturer. Choosing a package requires easy to solder, small size, better
heat transfer to the surroundings, number of I/O pins available etc.
h. Features available: There are plenty of on-chip features available like CPU
low power modes, timers, PWM output etc. Increase in number of features
increases the cost of the chip.
2. External Memory: External memory is used secondary storage. The amount of external
memory requirement depends on the application. For example, embedded system with
OS will require large amount of memory for system and user files.
3. Input-Output Devices: Number and type input and output devices are purely dependent
on the application. For example, a weather monitoring system requires measurement
of the parameters like temperature and humidity but gas leakage system requires
measurement of specific gas concentration in the air. So, the sensors used in the
application will be different. Some of the applications require user interaction which
can be switch, touch screen etc. The parameters considered for selecting input and
output devices are
a. Functionality: The device should be able to function as per the requirement.
b. Interface: Type of the interface used to connect with the device.
c. Cost: Cost of the device should be as low as possible.
d. Accuracy: Device should be able to perform accurate results. For example,
a temperature sensor should measure the temperature within the tolerance
limits.
e. Reliability: Device should be able to perform properly in different
environments.
f. Support: Hardware and software support should be available from the
manufacturer or third parties for functionality and calibration.
4. Custom Hardware: Custom hardware are only used when there are no available options
in accordance with the requirements of the application or the options available are
complex to implement and costly. ASICs can be used in applications, where power
consumption by the system should be very small or the speed of the system should be
very high, which is not possible with FPGAs and microcontroller.

24
2.8.2 Overall Criteria for selecting components
Following points should be kept in mind, while selecting the components for the embedded
system:
1. Development Cost: The cost of the overall system should be as low as possible,
fulfilling all the requirements of the system.
2. Lifetime: The lifetime of the system should as more as possible
3. Environment: System should not pollute the environment.
4. Safety: System should be safe for the users and intermediate resellers.
5. Maintenance: Maintenance cost and time should be as low as possible and should
be easily done by the users or service providers.
6. Size, shape and weight: In most cases, it is preferred to have minimum size and
weight but can have specific size or weight depending on the application. Shape of
the system is purely dependent on the application.
7. Reliable: The hardware and software of the system should work properly in
different conditions.
8. Availability of the components: The components should be easily available in the
market at the time of development and maintenance.
9. Power consumption: The power consumed by the system should be as low as
possible especially in battery operated systems.

25
CHAPTER 3

8051 MICROCONTROLLER

3.1 Introduction

Intel first produced a microcontroller in 1976 under the name MCS-48, which was an 8
bit microcontroller. Later in 1980 they released a further improved version (which is also 8 bit),
under the name MCS-51. The most popular microcontroller 8051 belongs to the MCS-51 family
of microcontrollers by Intel. Following the success of 8051, many other semiconductor
manufacturers released microcontrollers under their own brand name but using the MCS-51 core.
Global companies and giants in semiconductor industry like Microchip, Zilog, Atmel, Philips,
Siemens released products under their brand name. The specialty was that all these devices could
be programmed using the same MCS-51 instruction sets. They basically differed in support device
configurations like improved memory, presence of an ADC or DAC etc. Intel then released its first
16-bit microcontroller in 1982, under name MCS-96
3.1.1 8051 Microcontroller Packaging

Availability of various packages change from device to device. The most commonly used is Dual
Inline Package (40 pins) – known popularly as DIP. 8051 is also available in QFP (Quad Flat
Package), TQFP (Thin Quad Flat Package), PQFP (Plastic Quad Flat Package) etc. For explaining
the pin diagram, we have used a 40 pin DIP IC as model.

3.2 8051 Microcontroller Architecture

It’s possible to explain microcontroller architecture to a great detail, but we are limiting scope of
this manual to internal architecture, pin configuration, program memory and data memory
organization. The basic architecture remains same for the MCS-51 family. In general all
microcontrollers in MCS- 51 family are represented by XX51, where XX can take values like 80,
89 etc.

3.2.1 Schematic and Features

Fig 3.1: Schematic of 8051

26
The general schematic diagram of 8051 microcontrollers is shown above. We can see 3 system
inputs, 3 control signals and 4 ports (for external interfacing). A Vcc power supply and ground is
also shown. Now let’s explain and go through each in detail. System inputs are necessary to make
the micro controller functional. So the first and most important of this is power, marked as Vcc
with a GND (ground potential). Without proper power supply, no electronic system would work.
XTAL 1 and XTAL 2 are for the system clock inputs from crystal clock circuit. RESET input is
required to initialize microcontroller to default/desired values and to make a new start.
There are 3 control signals, EA, PSEN and ALE. These signals known as External Access (EA),
Program Store Enable (PSEN), and Address Latch Enable (ALE) are used for external memory
interfacing.
Take a look at the schematic diagram below (a functional microcontroller)

As mentioned above, control signals are used for external memory interfacing. If there is no
requirement of external memory interfacing then, EA pin is pulled high (connected to Vcc) and
two others PSEN and ALE are left alone. You can also see a 0.1 micro farad decoupling capacitor
connected to Vcc (to avoid HF oscillations at input).

There are four ports numbered 0,1,2,3 and called as Port 0, Port 1, Port 2 and Port 3 which are
used for external interfacing of devices like DAC, ADC, 7 segment display, LED etc. Each port
has 8 I/O lines and they all are bit programmable.

27
3.2.2 8051 Pin Diagram & Description

Fig 3.2: Pin diagram of 8051 microcontroller


For describing pin diagram and pin configuration of 8051, we are taking into consideration a 40
pin DIP (Dual inline package). Now lets go through pin configuration in detail.
Pin-40 : Named as Vcc is the main power source. Usually its +5V DC. You may note some pins
are designated with two signals (shown in brackets).
Pins 32-39: Known as Port 0 (P0.0 to P0.7) – In addition to serving as I/O port, lower order address
and data bus signals are multiplexed with this port (to serve the purpose of external memory
interfacing). This is a bi directional I/O port (the only one in 8051) and external pull up resistors
are required to function this port as I/O.
Pin-31:- ALE aka Address Latch Enable is used to demultiplex the address-data signal of port 0
(for external memory interfacing.) 2 ALE pulses are available for each machine cycle.
Pin-30:- EA/ External Access input is used to enable or disallow external memory interfacing. If
there is no external memory requirement, this pin is pulled high by connecting it to Vcc.
Pin- 29:- PSEN or Program Store Enable is used to read signal from external program memory.
Pins- 21-28:- Known as Port 2 (P 2.0 to P 2.7) – in addition to serving as I/O port, higher order
address bus signals are multiplexed with this quasi bi directional port.
Pin 20:- Named as Vss – it represents ground (0 V) connection.
Pins 18 and 19:- Used for interfacing an external crystal to provide system clock.
Pins 10 – 17:- Known as Port 3. This port also serves some other functions like interrupts, timer
input, control signals for external memory interfacing RD and WR , serial communication signals
RxD and TxD etc. This is a quasi bi directional port with internal pull up.
Pin 9:- As explained before RESET pin is used to set the 8051 microcontroller to its initial values,
while the microcontroller is working or at the initial start of application. The RESET pin must be
set high for 2 machine cycles.

28
Pins 1 – 8:- Known as Port 1. Unlike other ports, this port does not serve any other functions. Port
1 is an internally pulled up, quasi bi directional I/O port.
3.2.3 8051 Internal Architecture

Fig 3.3: Architecture of 8051 microcontroller


The system bus connects all the support devices with the central processing unit. 8051 system bus
composes of an 8 bit data bus and a 16 bit address bus and bus control signals. From the figure
you can understand that all other devices like program memory, ports, data memory, serial
interface, interrupt control, timers, and the central processing unit are all interfaced together
through the system bus. RxD and TxD (serial port input and output) are interfaced with port 3.

3.2.4 8051 System Clock

Fig 3.4: 8051 clock circuit

29
An 8051-clock circuit is shown above. In general cases, a quartz crystal is used to make the clock
circuit. The connection is shown in figure 2.6 and note the connections to XTAL 1 and XTAL
2. In some cases external clock sources are used and you can see the various connections above.
Clock frequency limits (maximum and minimum) may change from device to device. Standard
practice is to use 12MHz frequency. If serial communications are involved then its best to use
11.0592 MHz frequency.

Fig 3.5: 8051 System clock

Okay, take a look at the above machine cycle waveform. One complete oscillation of the clock
source is called a pulse. Two pulses forms a state and six states forms one machine cycle. Also
note that, two pulses of ALE are available for 1 machine cycle.

3.2.5 8051 Reset Circuit

(A) (B)
Fig 3.6 : (A) Power on reset circuit (B) with Manual reset option

30
8051 can be reset in two ways 1) is power-on reset – which resets the 8051 when power is turned
ON and 2) manual reset – in which a reset happens only when a push button is pressed manually.
Two different reset circuits are shown above. A reset doesn’t affect contents of internal RAM. For
reset to happen, the reset input pin (pin 9) must be active high for atleast 2 machine cycles. During
a reset operation :- Program counter is cleared and it starts from 00H, register bank #0 is selected
as default, Stack pointer is initialized to 07H, all ports are written with FFH.

3.3 8051 Memory Organization

Before going deep into the memory architecture of 8051, let’s talk a little bit about two variations
available for the same. They are Princeton architecture and Harvard architecture. Princeton
architecture treats address memory and data memory as a single unit (does not distinguish
between two) whereas Harvard architecture treats program memory and data memory
as separate entities. Thus, Harvard architecture demands address, data and control bus for
accessing them separately whereas Princeton architecture does not demand any such separate bus.
Example: - 8051 micro controller is based on Harvard architecture and 8085 microprocessor is
based on Princeton architecture.
Thus 8051 has two memories:- Program memory and Data memory

3.3.1 Program memory organization

Fig 3.7: Program Memory organization

Now let’s dive into the program memory organization 0f 8051. It has an internal program of 4K
size and if needed an external memory can be added (by interfacing ) of size 60K maximum. So
in total 64K size memory is available for 8051 micro controller. By default, the External Access
(EA) pin should be connected Vcc so that instructions are fetched from internal memory initially.
When the limit of internal memory (4K) is crossed, control will automatically move to external
memory to fetch remaining instructions. If the programmer wants to fetch instruction from external

31
memory only (bypassing the internal memory), then he must connect External Access (EA) pin to
ground (GND).
8051 has a special feature of locking the program memory (internal) and hence protecting against
software piracy. This feature is enable by program lock bits. Once these bits are programmed,
contents of internal memory cannot be accessed using an external circuitry. However, locking the
software is not possible if external memory is also used to store the software code. Only internal
memory can be locked and protected. Once locked, these bits can be unlocked only by a memory-
erase operation, which in turn will erase the programs in internal memory too.
8051 is capable of pipelining. Pipelining makes a processor capable of fetching the next instruction
while executing previous instruction. It’s something like multi-tasking, doing more than one
operation at a time. 8051 is capable of fetching first byte of the next instruction while executing
the previous instruction.
3.3.2 Data memory organization

Fig 3.8: Internal and external data memory

In the MCS-51 family, 8051 has 128 bytes of internal data memory and it allows interfacing
external data memory of maximum size up to 64K. So the total size of data memory in 8051 can
be upto 64K (external) + 128 bytes (internal). Observe the diagram carefully to get more
understanding. So there are 3 separations/divisions of the data memory:- 1) Register banks 2)
Bit addressable area 3) Scratch pad area.

Fig 3.9: lower 128 byte of internal RAM

32
Register banks form the lowest 32 bytes on internal memory and there are 4 register banks
designated bank #0,#1, #2 and #3. Each bank has 8 registers which are designated as R0,R1…R7.
At a time only one register bank is selected for operations and the registers inside the selected bank
are accessed using mnemonics R0..R1.. etc. Other registers can be accessed simultaneously only
by direct addressing. Registers are used to store data or operands during executions. By default
register bank #0 is selected (after a system reset).
The bit addressable ares of 8051 is usually used to store bit variables. The bit addressable area is
formed by the 16 bytes next to register banks. They are designated from address 20H to 2FH (total
128 bits). Each bits can be accessed from 00H to 7FH within this 128 bits from 20H to 2FH. Bit
addressable area is mainly used to store bit variables from application program, like status of an
output device like LED or Motor (ON/OFF) etc. We need only a bit to store this status and using
a complete byte addressable area for storing this is really bad programming practice, since it results
in wastage of memory.
The scratch pad area is the upper 80 bytes which is used for general purpose storage. Scratch pad
area is from 30H to 7FH and this includes stack too.

33
Chapter 4

Embedded System Development (ESD) board


4.1 Introduction: ESD board stands for embedded system development board. It was designed
and developed at ETI Labs for teaching the concepts of embedded systems practically. It is based
on 8051 microcontroller and offers wide range of features. ESD board has all the basics
components to get started with 8051. It comes with nuvoTon w78E052DDG which compatible to
8052 microcontroller. The microcontroller comes with built in serial bootloader, hence no external
programmer is required. Fig 4.1 shows the picture of ESD board.

Fig 4.1 ESD board

Fig 4.2Components of ESD board

34
4. 2 Features:
• Microcontroller:
• 8051-based CMOS microcontroller with 6-clock High-Speed Core
• 20 MHz at 6 clks/cycle, 40 MHz at 12 clks/cycle
• 256 B RAM, 8KB ISP Flash with 2KB LDROM (Bootloader)
• Up to 36 I/O pins
• Interrupt system with 8 sources and 4 priority levels
• 3 16-bit timer/counters, 1 Watchdog timer
• 1 full-duplex UART, 1 Power-Management Unit
• On board programmer
• No need to buy a separate programmer
• Automatic reset after programming
• USB connector for easy programming
• On board components for interfacing
• 4 general purpose LEDs
• 2 push buttons – can be used for general purpose, interrupts and counter.
• 7-15 volt input through DC jack and output for interfacing high-voltage
components like motors
• 3.3 volt output for interfacing various sensors and communication modules which
can work only on 3.3 v.
• Connectors for Bluetooth module and LCD
• All the GPIO pins of the controller are provided on the board
• Slide-switch for switching between programming and normal UART operation –
no need to remove wires/components during programming

4.2.1 W78E052D
The W78E054D/W78E052D series is an 8-bit microcontroller which can accommodate a wider
frequency range with low power consumption. The instruction set for the W78E054D/W78E052D
series is fully compatible with the standard 8052.

The W78E054D/W78E052D series contains 16K/8K bytes Flash EPROM programmable by


hardware writer; a 256 bytes RAM; four 8-bit bi-directional (P0, P1, P2, P3) and bit-addressable
I/O ports; an additional 4-bit I/O port P4; three 16-bit timer/counters; a hardware watchdog timer
and a serial port. These peripherals are supported by 8 sources 4-level interrupt capability. To
facilitate programming and verification, the Flash EPROM inside the W78E054D/W78E052D
series allows the program memory to be programmed and read electronically. Once the code is
confirmed, the user can protect the code for security.

35
The W78E054D/W78E052D series microcontroller has two power reduction modes, idle mode
and power-down mode, both of which are software selectable. The idle mode turns off the
processor clock but allows for continued peripheral operation. The power-down mode stops the
crystal oscillator for minimum power consumption. The external clock can be stopped at any time
and in any state without affecting the processor. The W78E054D/W78E052D series contains In-
System Programmable (ISP) 2KB LDROM for loader program, operating voltage from 3.3V to
5.5V.

Fig 4.3 : Pin diagram of W78E052D

It provides following features:

• Fully static design 8-bit CMOS • 64KB program memory address space
microcontroller
• 64KB data memory address space
• Optional 12T or 6T mode
• Four 8-bit bi-directional ports
ü 12T Mode, 12 clocks per machine cycle
operation (default), Speed up to 40 • 8-sources, 4-level interrupt capability
MHz/5V
ü 6T Mode, 6 clocks per machine cycle • One extra 4-bit bit-addressable I/O port,
operation set by the writer, Speed up to additional INT2 / INT3 (available on
20 MHz/5V PQFP, PLCC and LQFP package)
• Wide supply voltage of 2.4V to 5.5V

36
• Temperature grade is (-40oC~85oC) • Three 16-bit timer/counters

• Pin and Instruction-sets compatible with • One full duplex serial port
MCS-51
• Watchdog Timer
• 256 bytes of on-chip scratchpad RAM
• EMI reduction mode
• 16K/8K bytes electrically
erasable/programmable Flash EPROM • Software Reset

• 2K bytes LDROM support ISP function • Built-in power management with idle
mode and power down mode

• Code protection

• Packages: DIP40, PLCC44, PQFP44,


LQFP48, TQFP44

4.3 Instructions to use ESD board

To use ESD board follow the below instructions

1. Download & install IDE for programming and creating hex file: Recommended Keil IDE
for Editing, Compiling, Debugging and Simulation
2. Download and install CH340G driver to connect ESD board with your PC
3. Download and install Nuvoton Flash tool to burn your code into ESD board

To download the above software and driver go to www.etilabs.com/products/esd-board/

and click on download software button.

37
1. Open uVision IDE and click on Project->New uVision Project.

2. Choose a folder to create a new project (or create a new folder).

38
3. Type a Project name and click on Save.

4. Search W78E052D and select the target microcontroller.

39
5. Expand Target 1 then right click on Source Group 1 and click on Add New Item to Source
Group 1.

6. Select C File (.C)/Asm File (.a) for writing the code into C/Assembly language, then name
the file and click on Add.

40
Target options

7. Write the code in the file then click on Target Option button.

8. Select Output then tick the check box for Create Hex File and click OK.

41
9. Click on build target button.

Build

4.3.2 Programming ESD using Nuvoton

1. Connect your ESD board to Laptop/PC via USB B type cable.


2. Open Nuvoton ISP-ICP utility and choose ISP by COM Port.
3. Select the COM port from the drop down as detected by computer in device manager.
4. Choose the controller as W78E052D.
5. Click on Load File then browse and select the “.hex” file.
6. Click on Update chip to burn the “.hex” file in microcontroller’s flash memory.

42
CHAPTER 5

Getting started with ESD board


5.1 LED interfacing & programming:

There are 4 onboard LEDs already interfaced with the 8051 microcontroller on ESD board. The
LEDs are connected as follows:

LED Anode cathode

1 Vcc (5V) P1^0

2 Vcc (5V) P1^1

3 Vcc (5V) P1^2

4 Vcc (5V) P1^3

LED: A light-emitting diode (LED) is a semiconductor device that emits visible light when an
electric current passes through it. The light is not particularly bright, but in most LEDs it is
monochromatic, occurring at a single wavelength. The output from an LED can range from red (at
a wavelength of approximately 700 nanometers) to blue-violet (about 400 nanometers). Some
LEDs emit infrared (IR) energy (830 nanometers or longer); such a device is known as an infrared-
emitting diode (IRED).

Note: In case of ESD board the LED with glow when there is logic zero on pin. For example when
there is logic zero i.e 0V on P1^0 then the cathode of led will get 0v and anode of led is already
connected to Vcc or 5V, so the led will be in forward biased and hence will glow.

(a) (b)
Fig 5.1: (a) Image of Led and its symbol (b) LED circuit diagram

43
RGB LED: RGB LEDs consist of one red, one green, and one blue LED. By
independently adjusting each of the three, RGB LEDs are capable of producing a wide color
gamut. Unlike dedicated-color LEDs, however, these obviously do not produce pure wavelengths.

(a) (b)
Fig 5.2 (a) Common Anode (b) RGB led

Current-limiting: It is used to achieve a particular current in the LED. Resistors are used with
LEDs to limit the current flowing through the LED to a safe level. Most 3mm and 5mm LEDs
will operate close to their peak brightness at a current of 20 mA.

LED Blinking: Led Blinking is achieved by making the led on and off with some delay. Time
delay can be created in two ways:

44
• Using the 8051 timer
• Using simple for Loops

In creating a time delay using for loop following factors needs to be considered:

• Number of machine cycles and no. of clock periods per machine cycles
• Crystal oscillator frequency. Duration of clock period for machine cycle is function of crystal
frequency
• Compiler selected. Accuracy of time delay is mainly due to the compiler used.

5.1.1 Interfacing Led and blink

Interfacing diagram:

Program:

Assembly Embedded C
LED EQU P1.0 #include<reg51.h>
ORG 00H sbit LED1=P1^0; //variable LED1 has the value of pin 0 of
BLINK: port1
SETB LED; LED OFF void delay(unsigned int i); //prototype of delay function
ACALL DELAY void main(void){
CLR LED ; LED ON while(1){ //infinite loop
ACALL DELAY LED1=0; //LED1 is ON
AJMP BLINK delay(75); //calling the delay function with 75 input
LED1=1;
DELAY: ;Function for delay delay(75);
MOV R0, #10 }
LOOP2: MOV R1, #200 }
LOOP1: MOV R2, #200 //definition of delay function
LOOP: DJNZ R2, LOOP void delay(unsigned int i){
DJNZ R1, LOOP1 unsigned int k;
DJNZ R0, LOOP2 unsigned int j;
RET for(j=0;j<i;j++) //loop goes from 0 to input(75 )
END for(k=0;k<7500;k++); //loop goes from 0 to 7500
}

45
5.1.2 Alternate led blinking pattern using 8/4 LEDs

Interfacing diagram:

Program:

Assembly Embedded C
LEDS EQU P1 #include<reg51.h>
ORG 00H void delay();
BLINK: void main(){
MOV LEDS, #01010101B ; 4 LEDs
while(1) {
ACALL DELAY
MOV LEDS, #10101010B ;alternate 4 LEDs P1=0X55;
ACALL DELAY delay();
AJMP BLINK P1=0XAA;
DELAY: ;Function for delay delay();
MOV R0, #10 }
LOOP2: MOV R1, #200 }
LOOP1: MOV R2, #200
void delay(){
LOOP: DJNZ R2, LOOP
DJNZ R1, LOOP1 int i,j;
DJNZ R0, LOOP2 for(i=0;i<1000;i++)
RET for(j=0;j<50;j++);
END }

5.1.3 Interfacing RGB led and Generate Red, Blue, Green sequence in RGB LED

Interfacing diagram:

46
Program:

Assembly
LED_R EQU P2.0 CLR LED_G
LED_G EQU P2.1 SETB LED_B ;Blue Colour
LED_B EQU P2.2 ACALL DELAY
ORG 00H AJMP BLINK
BLINK: DELAY:
SETB LED_R ;Red colour MOV R0, #10
CLR LED_G LOOP2: MOV R1, #200
CLR LED_B LOOP1: MOV R2, #200
ACALL DELAY LOOP: DJNZ R2, LOOP
CLR LED_R DJNZ R1, LOOP1
SETB LED_G ;Green Colour DJNZ R0, LOOP2
CLR LED_B RET
ACALL DELAY END
CLR LED_R

Embedded C
#include <reg51.h> delay(1000);
sbit RED=P1^0; RED= GREEN= BLUE=0;
sbit GREEN=P1^1; delay(1000);
sbit BLUE=P1^2; }
void delay(); }
int main(void) void delay()//function to cause delay
{ {
while(1) int i,j;
{ for(i=0;i<1000;i++)
RED=1; GREEN=BLUE=0;
for(j=0;j<50;j++);
delay(1000);
}
GREEN=1; RED=BLUE=0;
delay(1000);
BLUE=1; RED=GREEN=0;

47
5.1.4 Traffic light application

Interfacing diagram:

Program:

Assembly
LED_R EQU P1.0 SETB LED_R
LED_Y EQU P1.1 SETB LED_Y
LED_G EQU P1.2 CLR LED_G ;Green LED ON ACALL
ORG 00H DELAY ;with large delay
BLINK: ACALL DELAY
CLR LED_R ;Red LED ON ACALL DELAY
SETB LED_Y ;with large delay AJMP BLINK
SETB LED_G DELAY: ;Function for delay
ACALL DELAY MOV R0, #10
ACALL DELAY LOOP2: MOV R1, #200
ACALL DELAY LOOP1: MOV R2, #200
ACALL DELAY LOOP: DJNZ R2, LOOP
SETB LED_R DJNZ R1, LOOP1
CLR LED_Y ;Yellow LED ON DJNZ R0, LOOP2
SETB LED_G ;with small delay RET
ACALL DELAY END

Embedded C
//sequence: GREEN->YELLOW->RED LED1=0; LED2=1; LED3=1;
#include<reg51.h> for(i=0;i<70;i++)
sbit LED1=P1^0; //red delay();
sbit LED2=P1^1; //blue }
sbit LED3=P1^2; //green }
int i; //definition of delay function
void delay(); //prototype of delay function void delay(){
void main() { TMOD=0x11;
while(1) //infinite loop TH0=00;
{ TL0=00;
LED1=1; LED2=1; LED3=0; TR0=1;
for(i=0;i<70;i++) while(TF0==0);
delay(); TR0=0;
LED1=1; LED2=0; LED3=1; TF0=0;
for(i=0;i<30;i++) }
delay();

48
5.2 Pushbutton & its programming
A push-button or simply button is a simple switch mechanism for controlling some aspect of
a machine or a process. Buttons are most often biased switches, though even many un-biased
buttons (due to their physical nature) require a spring to return to their un-pushed state.

Fig 5.3: Push button and its internal circuitry

Operation: The above push button is a momentary type push button which return to its original
position after it is released.

Fig 5.4: push button operation

5.2.1 Interfacing pushbutton controlling led with it

Interfacing diagram:

49
Program:

Assembly Embedded C
PB EQU P3.5 #include<reg51.h>
LED EQU P1.0 int i,j;
ORG 00H sbit led=P1^0;
SETB PB ;Push Button as input sbit push=P3^5;
CHECK: void main(){
JNB PB, LED_ON ;if push button not while(1){ //infinite loop
pressed if(push==0) //if value of push is 0
SETB LED ;then turn off LED led=0; //LED ON
AJMP CHECK else
LED_ON: CLR LED ;else turn on LED led=1; //LED OFF
AJMP CHECK }
END }

5.2.2 Read the signal with pressing of push button on logic analyzer

Program:

Assembly Embedded C
;Program: Read the signal with pressing of push #include<reg51.h>
button on logic analyzer int i,j;
PB EQU P3.5 sbit led=P1^0;
LED EQU P1.0 sbit push=P3^5;
ORG 00H void main(){
SETB PB ;Push Button as input while(1) //infinite loop
CHECK: {
JNB PB, LED_ON ;if push button not if(push==0) {
pressed led=0; //LED ON
SETB LED ;then turn off LED }
AJMP CHECK Else
LED_ON: CLR LED ;else turn on LED led=1; //LED OFF
AJMP CHECK }
END }

50
Chapter 6

Sensor interfacing & programming


6.1 Sensor: A sensor is a device that detects and responds to some type of input from the physical
environment. The specific input could be light, heat, motion, moisture, pressure, or any one of a
great number of other environmental phenomena. The output is generally a signal that is converted
to human-readable display at the sensor location or transmitted electronically over a network for
reading or further processing.

There are basically two types of sensor based upon the type of output it generates.

They are Analog sensor & Digital sensor

Digital Sensor: A digital sensor is an electronic or electrochemical sensor, where data


conversion and data transmission are done digitally. Example of digital sensors are Touch sensor,
light sensor, motion sensor, Proximity sensor, temperature sensor etc

Fig 6.1

Digital Signals: Digital signals must have a finite set of possible values. The number of values in the set
can be anywhere between two and a-very-large-number-that’s-not-infinity. Most commonly digital signals
will be one of two values – like either 0V or 5V. Timing graphs of these signals look like square waves.

51
6.2 PIR Sensor

PIR-based motion detector is used to sense movement of people, animals, or other objects. They
are commonly used in burglar alarms and automatically-activated lighting systems. They are
commonly called simply "PIR", or sometimes "PID", for "passive infrared detector".

PIRs are basically made of a pyroelectric sensor (which you can see above as the round metal can
with a rectangular crystal in the center), which can detect levels of infrared radiation. Everything
emits some low level radiation, and the hotter something is, the more radiation is emitted. The
sensor in a motion detector is actually split in two halves. The reason for that is that we are looking
to detect motion (change) not average IR levels. The two halves are wired up so that they cancel
each other out. If one half sees more or less IR radiation than the other, the output will swing high
or low. Along with the pyroelectic sensor is a bunch of supporting circuitry, resistors and
capacitors.

Fig 6.2 PIR sensor

6.2.1 WAP to make the buzzer sound when PIR sensor detects an intruder

Interfacing diagram:

52
Program:

Assembly Embedded C
;Program: Make the buzzer sound when intruder #include<reg51.h>
detected int i,j;
BUZZER EQU P2.0 sbit BUZZER=P2^0;
PIR EQU P2.1 sbit PIR=P2^1;
ORG 00H void main(){
SETB PIR ;PIR as input while(1) {
CHECK: if(push==0) {
JNB PIR, Buzzer_ON ;if no motion BUZZER=0; //BUZZER ON
detected }
CLR BUZZER ;turn OFF Buzzer else
AJMP CHECK BUZZER=1; //BUZZER OFF
Buzzer_ON: SETB BUZZER ;else turn ON }
Buzzer }
AJMP CHECK
END

6.3 LDR sensor

A Light Dependent Resistor (LDR) or a photo resistor is a device whose resistivity is a function
of the incident electromagnetic radiation. Hence, they are light sensitive devices. They are also
called as photo conductors, photo conductive cells or simply photocells. They are made up of
semiconductor materials having high resistance. A light dependent resistor works on the principle
of photo conductivity. Photo conductivity is an optical phenomenon in which the materials
conductivity is increased when light is absorbed by the material.

Fig 6.3 LDR sensor module

53
6.3.1 WAP to turn on all the LEDs of a port when there is not enough light in the room using LDR

Interfacing diagram:

Program:

Assembly Embedded C
;Program: Turn ON LEDs if light is not sufficient #include<reg51.h>
LEDS EQU P1 ;P1.3-P1.0 #define LEDS P1
LDR EQU P2.0 sbit LDR=P2^0;
ORG 00H void delay();
SETB ;LDR as input void main()
CHECK: {
JNB LDR, LED_ON ;if natural light while(1) {
present If(LDR==1)
MOV LEDS,#255 ;turn off LEDs LEDS =0X00;
AJMP CHECK else
LED_ON: MOV LEDS,#0 ;else turn on LEDS =0XFF;
LEDs }
AJMP CHECK }
END

6.4 Touch sensor

Touch sensors are also called as tactile sensors and are sensitive to touch, force or pressure. They
are one of the simplest and useful sensors. The working of a touch sensor is similar to that of a
simple switch. When there is contact with the surface of the touch sensor, the circuit is closed
inside the sensor and there is a flow of current. When the contact is released, the circuit is opened
and no current flows.

54
6.4.1 WAP to turn on LED when push button is pressed and make the buzzer sound when touch
sensor is touched

Interfacing diagram:

Program:

Assembly Embedded C
;Program: Turn ON LED when push button is //Turn ON LED when push button pressed and
pressed and make the buzzer sound when touch turn ON buzzer when touch sensor pressed
sensor is touched #include<reg51.h> //include library to use
BUZZER EQU P2.0 registers defined in it
LED EQU P1.0 sbit push1=P3^2;
PB EQU P3.2 sbit sensor=P2^1;
TOUCH EQU P2.1 sbit buzzer =P2^0;
ORG 00H void main()
SETB PB;Push Button as input {
SETB TOUCH ;Touch as input while(1) //infinte loop
CHECK: JNB PB, LED_ON ;if push button {
not pressed buzzer=1; //BUZZER OFF
SETB LED ;turn off LED P1=255; //all LEDs OFF
AJMP CHECK_Touch
LED_ON: CLR LED ;else turn on LED if(push1==0)
CHECK_Touch: JNB TOUCH, Buzzer_ON ;if Touch {
detected P1=0; //all led on
CLR BUZZER ;turn ON Buzzer if(sensor)
AJMP CHECK buzzer=0; Buzzer on
Buzzer_ON: SETB BUZZER ;else turn OFF }
Buzzer }
AJMP CHECK }
END

55
6.5 Sound sensor

The Sound Sensor is a small board that combines a microphone and some processing circuitry. It
provides not only an audio output, but also a binary indication of the presence of sound, and an
analog representation of its amplitude. It is a simple microphone. Based on the power
amplifier LM386 and the electric microphone, it can be used to detect the sound strength of the
environment. The value of output can be adjusted by the potentiometer.

Fig 6.4 sound sensor

6.5.1 WAP to turn ON an LED to indicate the detection of sound

Interfacing diagram:

Program:

Assembly Embedded C
;Program: WAP to turn ON an LED to indicate the #include<reg51.h>
detection of sound int i,j;
LED EQU P1.0 sbit led=P1^0;
SOUND EQU P2.0 sbit SOUND=P2^0;
ORG 00H void main(){
SETB SOUND ;sound sensor as input while(1) //infinite loop
CHECK: {
JNB SOUND, LED_ON ;if light not if(SOUND==1) //if value of push is 0
present {
CLR LED ;turn ON LED led=0; //LED ON
AJMP CHECK }
LED_ON: SETB LED ;else turn OFF else
LED led=1; //LED OFF
AJMP CHECK }
END }

56
CHAPTER 7

Display interfacing & programming

7.1Seven-segment
The 7-segment display, also written as “seven segment display”, consists of seven LEDs (hence
its name) arranged in a rectangular fashion. Each of the seven LEDs is called a segment because
when illuminated the segment forms part of a numerical digit (both Decimal and Hex) to be
displayed. An additional 8th LED is sometimes used within the same package thus allowing the
indication of a decimal point, (DP) when two or more 7-segment displays are connected together
to display numbers greater than ten.

Fig 7.1: Seven segment display

Each one of the seven LEDs in the display is given a positional segment with one of its connection
pins being brought straight out of the rectangular plastic package. These individually LED pins
are labelled from a through to g representing each individual LED. The other LED pins are
connected together and wired to form a common pin.
So by forward biasing the appropriate pins of the LED segments in a particular order, some
segments will be light and others will be dark allowing the desired character pattern of the number
to be generated on the display. This then allows us to display each of the ten decimal
digits 0 through to 9 on the same 7-segment display.
The displays common pin is generally used to identify which type of 7-segment display it is. As
each LED has two connecting pins, one called the “Anode” and the other called the “Cathode”,
there are therefore two types of LED 7-segment display called: Common Cathode (CC)
and Common Anode (CA).
The difference between the two displays, as their name suggests, is that the common cathode has
all the cathodes of the 7-segments connected directly together and the common anode has all the
anodes of the 7-segments connected together and is illuminated as follows.

57
Common Cathode (CC) – In the common cathode display, all the cathode connections of the LED
segments are joined together to logic “0” or ground. The individual segments are illuminated by
application of a “HIGH”, or logic “1” signal via a current limiting resistor to forward bias the
individual Anode terminals (a-g).

Fig 7.2 Common Cathode seven segment

Common Anode (CA): In the common anode display, all the anode connections of the LED
segments are joined together to logic “1”. The individual segments are illuminated by applying a
ground, logic “0” or “LOW” signal via a suitable current limiting resistor to the Cathode of the
particular segment (a-g).

Fig 7.3 Common Cathode seven segment

In general, common anode displays are more popular as many logic circuits can sink more current
than they can source. Also note that a common cathode display is not a direct replacement in a
circuit for a common anode display and vice versa, as it is the same as connecting the LEDs in
reverse, and hence light emission will not take place.

58
Depending upon the decimal digit to be displayed, the particular set of LEDs is forward biased.
For instance, to display the numerical digit 0, we will need to light up six of the LED segments
corresponding to a, b, c, d, e and f. Then the various digits from 0 through 9 can be displayed using
a 7-segment display as shown in table 7.1
Table 7.1

7.1.1 Interface 7 segment and display 0 to 9 with some delay

Interfacing diagram:

59
Program:

Assembly Embedded C
SEVSEG EQU P1 #include<reg51.h>
ORG 00H void main(){
BLINK: while(1){
MOV SEVSEG, #0E7H ;DISPLAY 0 P1=0XE7; //DISPLAY 0
ACALL DELAY for(x=0;x<=20; x++){
MOV SEVSEG, #21H ;DISPLAY 1 T0Delay_50ms();
ACALL DELAY }
MOV SEVSEG, #0CBH ;DISPLAY 2 P1=0X21; //DISPLAY 1
ACALL DELAY for(x=0;x<=20; x++){
MOV SEVSEG, #0ABH ;DISPLAY 3 T0Delay_50ms();
ACALL DELAY }
MOV SEVSEG, #2DH ;DISPLAY 4 P1=0XCB; //DISPLAY 2
ACALL DELAY for(x=0;x<=20; x++){
MOV SEVSEG, #0AEH ;DISPLAY 5 T0Delay_50ms();
ACALL DELAY }
MOV SEVSEG, #0EEH ;DISPLAY 6 P1=0XAB; //DISPLAY 3
ACALL DELAY for(x=0;x<=20; x++){
MOV SEVSEG, #23H ;DISPLAY 7 T0Delay_50ms();
ACALL DELAY }
MOV SEVSEG, #0EFH ;DISPLAY 8 P1=0X2D; //DISPLAY 4
ACALL DELAY for(x=0;x<=20; x++){
MOV SEVSEG, #0AFH ;DISPLAY 9 T0Delay_50ms();
ACALL DELAY }
AJMP BLINK P1=0XAE; //DISPLAY 5
for(x=0;x<=20; x++){
DELAY: ;Function for delay T0Delay_50ms();
MOV R0, #10 }
LOOP2: MOV R1, #200 P1=0XEE; //DISPLAY 6
LOOP1: MOV R2, #200 for(x=0;x<=20; x++){
LOOP: DJNZ R2, LOOP T0Delay_50ms();
DJNZ R1, LOOP1 }
DJNZ R0, LOOP2 P1=0X23; //DISPLAY 7
RET for(x=0;x<=20; x++){
END T0Delay_50ms();
}
P1=0XEF; //DISPLAY 8
for(x=0;x<=20; x++){
T0Delay_50ms();
}
P1=0XAF; //DISPLAY 9
for(x=0;x<=20; x++){
T0Delay_50ms();
}
}
}}

60
7.2 LCD

LCDs are used as output peripheral for displaying data. They are economical and easily
programmable. A 16x2 LCD means it can display 16 characters per line and there are 2 such lines.
In this LCD each character is displayed in 5x7 pixel matrix. This LCD has two registers, namely,
Command and Data. The command register stores the command instructions given to the LCD. A
command is an instruction given to LCD to do a predefined task like initializing it, clearing its
screen, setting the cursor position, controlling display etc. The data register stores the data to be
displayed on the LCD. The data is the ASCII value of the character to be displayed on the LCD.

Fig 7.4 : 2x16 LCD front and back view

The table below shows the Pin functions of an LCD

61
16×2 LCD module commands

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

LCD ON, Cursor ON, Cursor blinking


0F ON

01 Clear screen

02 Return home

04 Decrement cursor

06 Increment cursor

0E Display ON ,Cursor blinking OFF

80 Force cursor to the beginning of 1st line

C0 Force cursor to the beginning of 2nd line

38 Use 2 lines and 5×7 matrix

83 Cursor line 1 position 3

3C Activate second line

08 Display OFF, Cursor OFF

C1 Jump to second line, position1

OC Display ON, Cursor OFF

C1 Jump to second line, position1

C2 Jump to second line, position2

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

§ Send 38H to the 8-bit data line for initialization


§ Send 0FH for making LCD ON, cursor ON and cursor blinking ON.
§ Send 06H for incrementing cursor position.
§ Send 01H for clearing the display and return the cursor.

Sending data to the LCD:

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.

§ Make R/W low.


§ Make RS=0 if data byte is a command and make RS=1 if the data byte is a data to be
displayed.
§ Place data byte on the data register.
§ Pulse E from high to low.
§ Repeat above steps for sending another data.

7.2.1 Display ETI Labs on LCD without using busy flag

Interfacing diagram:

63
Assembly Embedded C
E EQU P2.7 #include<reg51.h>
RS EQU P2.6 sbit RS=P2^6;
LCD EQU P0
sbit EN=P2^7;
ORG 00H
MAIN: char a[7]={ 'E','T','I',’ ‘,'L','A','B','S' };
CLR E void cmd(unsigned char cmd);
CLR RS void cmdlcd(unsigned char cmd[]);
MOV R4, #38H ;Use 2 lines and 5×7 matrix for LCD void delay();
ACALL LCD_COMMAND void main(){
ACALL DELAY
while(1){
MOV R4, #0CH ;LCD ON, Cursor OFF
ACALL LCD_COMMAND cmd(0x38); delay(); //initialising
ACALL DELAY LCD
MOV R4, #01H ;LCD clear cmd(0x0E); delay();
ACALL LCD_COMMAND cmd(0x01); delay();
ACALL DELAY cmd(0x80); delay();
MOV R4, #'E' ;Display "ETI Labs" on LCD first row
cmdlcd(a); delay();
ACALL LCD_DATA
MOV R4, #'T' }
ACALL LCD_DATA }
MOV R4, #'I' //to send command
ACALL LCD_DATA void cmd(unsigned char cmd)
MOV R4, #' ' {
ACALL LCD_DATA
P0=cmd;
MOV R4, #'L'
ACALL LCD_DATA RS=0; //for command
MOV R4, #'a' //RW=0; //for write
ACALL LCD_DATA EN=1; //to enable
MOV R4, #'b' delay();
ACALL LCD_DATA EN=0; //disable
MOV R4, #'s'
}
ACALL LCD_DATA
AJMP MAIN //to send data
LCD_COMMAND: ;Function for LCD command void cmdlcd(unsigned char cmd[7]){
CLR RS int i;
MOV LCD, R4 for(i=0;i<7;i++)
SETB E {
ACALL DELAY
P0=cmd[i];
CLR E
RET RS=1; //send data
LCD_DATA: ;Function for LCD data //RW=0; //write
SETB RS EN=1;
MOV LCD, R4 delay();
SETB E EN=0;
ACALL DELAY
}
CLR E
RET }
DELAY: ;Function for delay //to cause some delay
MOV R7, #200 void delay()
LOOP1: MOV R6, #200 {
LOOP: DJNZ R6, LOOP int i,j;
DJNZ R7, LOOP1
for(i=0;i<1000;i++)
RET
END for(j=0;j<10;j++);
}

64
7.2.2 Take the input from 4 different PB and display a message corresponding to each button

Interfacing diagram:

Assembly
E EQU P2.7 MOV R4, #'t'
RS EQU P2.6 ACALL LCD_DATA
LCD EQU P0 MOV R4, #'o'
PB1 EQU P3.2 ACALL LCD_DATA
PB2 EQU P3.5 MOV R4, #'n'
PB3 EQU P3.6 ACALL LCD_DATA
PB4 EQU P3.7 CHECK: JB PB1, CHECK2 ;Push Button 1
ORG 00H MOV R4, #87H
MAIN: ACALL LCD_COMMAND
SETB PB1 ;Push Buttons as input ACALL DELAY
SETB PB2 MOV R4, #'1' ;Display 1
SETB PB3 ACALL LCD_DATA
SETB PB4 AJMP CHECK
CLR E CHECK2: JB PB2, CHECK3 ;Push Button 2
CLR RS MOV R4, #87H
MOV R4, #38H ;Use 2 lines and 5×7 ACALL LCD_COMMAND
matrix for LCD ACALL DELAY
ACALL LCD_COMMAND MOV R4, #'2' ;Display 2
ACALL DELAY ACALL LCD_DATA
MOV R4, #0CH ;LCD ON, Cursor OFF AJMP CHECK
ACALL LCD_COMMAND CHECK3: JB PB3, CHECK4 ;Push Button 3
ACALL DELAY MOV R4, #87H
MOV R4, #01H ;LCD clear ACALL LCD_COMMAND
ACALL LCD_COMMAND ACALL DELAY
ACALL DELAY MOV R4, #'3' ;Display 3
MOV R4, #'B' ;Display "Button" on LCD ACALL LCD_DATA
first row AJMP CHECK
ACALL LCD_DATA MOV R4, #'t'

65
MOV R4, #'u' ACALL LCD_DATA
ACALL LCD_DATA MOV R4, #'o'
MOV R4, #'t' ACALL LCD_DATA
ACALL LCD_DATA MOV R4, #'n'
ACALL LCD_DATA ACALL DELAY
CHECK: JB PB1, CHECK2 ;Push Button 1 MOV R4, #'4' ;Display 4
MOV R4, #87H ACALL LCD_DATA
ACALL LCD_COMMAND AJMP CHECK
ACALL DELAY LCD_COMMAND: ;Function for LCD
MOV R4, #'1' ;Display 1 command
ACALL LCD_DATA CLR RS
AJMP CHECK MOV LCD, R4
CHECK2: JB PB2, CHECK3 ;Push Button 2 SETB E
MOV R4, #87H ACALL DELAY
ACALL LCD_COMMAND CLR E
ACALL DELAY RET
MOV R4, #'2' ;Display 2 LCD_DATA: ;Function for LCD data
ACALL LCD_DATA SETB RS
AJMP CHECK MOV LCD, R4
CHECK3: JB PB3, CHECK4 ;Push Button 3 SETB E
MOV R4, #87H ACALL DELAY
ACALL LCD_COMMAND CLR E
ACALL DELAY RET
MOV R4, #'3' ;Display 3 DELAY: ;Function for delay
ACALL LCD_DATA MOV R1, #200
AJMP CHECK LOOP1: MOV R2, #200
CHECK4: JB PB4, CHECK ;Push Button 4 LOOP: DJNZ R2, LOOP
MOV R4, #87H DJNZ R1, LOOP1
ACALL LCD_COMMAND RET
END

66
Embedded C
#include<reg51.h> //include library to use registers {cmdlcd(a,5); delay();}
defined in it if(PB2==0)
sbit RS=P2^7; {cmdlcd(b,4); delay();}
sbit EN=P2^6; if(PB3==0)
sbit PB1=P3^2; {cmdlcd(c,2); delay();}
sbit PB2=P3^5; if(PB4==0)
sbit PB3=P3^6; {cmdlcd(d,3); delay();}
sbit PB4=P3^7; }
char a[5]="Hello"; }
char b[4]="This"; //to send command
char c[2]="is"; void cmd(unsigned char cmd)
char d[3]="LCD"; {
void cmd(unsigned char cmd); //to send command P2=cmd;
void cmdlcd(unsigned char cmd[],int); //to send data RS=0; //for command
void delay(); //to cause some delay //RW=0; //for write
void main(){ EN=1; //to enable
while(1) delay();
{ EN=0; //disable
cmd(0x38); delay(); //initialising LCD }
cmd(0x0E); delay(); //to send data
cmd(0x01); delay(); void cmdlcd(unsigned char cmd[7],int n)
cmd(0x80); delay(); {
if(PB1==0) int i;
for(i=0;i<n;i++) void delay()
{ {
P2=cmd[i]; int i,j;
RS=1; //send data for(i=0;i<1000;i++)
//RW=0; //write for(j=0;j<10;j++);
EN=1; }
delay();
EN=0;
}
}

67
Chapter 8

Keypad interfacing & programming


A keypad is a set of buttons arranged in a block or "pad" which bear digits, symbols or alphabetical
letters. Pads mostly containing numbers are called a numeric keypad. Numeric keypads are found
on alphanumeric keyboards and on other devices which require mainly numeric input such
as calculators, push-button telephones, vending machines, ATMs, Point of Sale
devices, combination locks, and digital door locks.

Internally, the structure of the hex keypad is very simple. Wires run in vertical columns (we call
them C1 to C4) and in horizontal rows (called R1 to R4). These 8 wires are available externally,
and will be connected to the lower 8 bits of the port. Each key on the keypad is essentially a switch
that connects a row wire to a column wire. When a key is pressed, it makes an electrical connection
between the row and column. The internal structure of the hex keypad is shown in Figure 8.1.

Fig 8.1 : Hex keypad (a) Internal structure of keypad (b) Keypad

The program identifies the pressed key by a method called column scanning. In this method a
particular row is kept low and other rows are held high. The logic status of each column line is
scanned. If a particular column is found low, then that means the key that comes in between that
column and row is short(pressed). Then the program registers that key being pressed. Then the
same procedure is applied for the subsequent rows and the entire process is repeated. For example
if row 1 is kept low and column 1 is found low during scanning, then that means key”1″ is pressed.
Full circuit diagram of interfacing hex keypad is shown below.

68
8.1 Interfacing hex keypad and display key pressed on 7-segment

Interfacing diagram:

Program:

Assembly
;Program: Display key pressed of keypad on seven JNB KR4, KEY_B
segment MOV KEYPAD, #11111011B ;column3 =
KC1 EQU P2.0 0, other columns = 1
KC2 EQU P2.1 JNB KR1, KEY_7 ;check all the rows
KC3 EQU P2.2 JNB KR2, KEY_8 ;and jump for display
KC4 EQU P2.3 JNB KR3, KEY_9
KR1 EQU P2.4 JNB KR4, KEY_C
KR2 EQU P2.5 MOV KEYPAD, #11110111B ;column4 =
KR3 EQU P2.6 0, other columns = 1
KR4 EQU P2.7 JNB KR1, KEY_STAR ;check all the rows
KEYPAD EQU P2 JNB KR2, KEY_0 ;and jump for display
SEVSEG EQU P1 JNB KR3, KEY_HASH
ORG 00H JNB KR4, KEY_D
CHECK_KB: AJMP CHECK_KB
MOV KEYPAD, #11111111B ;initially all KEY_1: MOV SEVSEG, #21H ;Display 1 on seven
1's at keypad segment
MOV KEYPAD, #11111110B ;column1 = AJMP CHECK_KB
0, other columns = 1 KEY_2: MOV SEVSEG, #0CBH ;Display 2
JNB KR1, KEY_1 ;check all the rows AJMP CHECK_KB
JNB KR2, KEY_2 ;and jump for display KEY_3: MOV SEVSEG, #0ABH ;Display 3
JNB KR3, KEY_3 AJMP CHECK_KB
JNB KR4, KEY_A KEY_A: MOV SEVSEG, #6FH ;Display A
MOV KEYPAD, #11111101B ;column2 = AJMP CHECK_KB
0, other columns = 1 KEY_4: MOV SEVSEG, #2DH ;Display 4
JNB KR1, KEY_4 ;check all the rows AJMP CHECK_KB
JNB KR2, KEY_5 ;and jump for display KEY_5: MOV SEVSEG, #0AEH ;Display 5
JNB KR3, KEY_6 AJMP CHECK_KB

69
KEY_6: MOV SEVSEG, #0EEH ;Display 6 KEY_C: MOV SEVSEG, #0C6H ;Display C
AJMP CHECK_KB AJMP CHECK_KB
KEY_B: MOV SEVSEG, #0ECH ;Display b KEY_STAR: MOV SEVSEG, #4CH ;Display *
AJMP CHECK_KB AJMP CHECK_KB
KEY_7: MOV SEVSEG, #23H ;Display 7 KEY_0: MOV SEVSEG, #0E7H ;Display 0
AJMP CHECK_KB AJMP CHECK_KB
KEY_8: MOV SEVSEG, #0EFH ;Display 8 KEY_HASH: MOV SEVSEG, #6DH ;Display #
AJMP CHECK_KB AJMP CHECK_KB
KEY_9: MOV SEVSEG, #0AFH ;Display 9 KEY_D: MOV SEVSEG, #0E9H ;Display D
AJMP CHECK_KB AJMP CHECK_KB
END

Embedded C
#include<reg51.h> P1=0x23; //7
sbit C1 = P2^0; }
sbit C2 = P2^1; void rowfind2() // finding the row for col 2
sbit C3 = P2^2; {
sbit C4 = P2^3; if(R1==0)
sbit R1 = P2^4; P1=0xCB; //2
sbit R2 = P2^5; if(R2==0)
sbit R3 = P2^6; P1=0xAE; //5
sbit R4 = P2^7; if(R3==0)
void rowfind1(); P1=0xEF; //8
void rowfind2(); if(R4==0)
void rowfind3(); P1=0xE7; //0
void rowfind4(); }
void main(){ void rowfind3() // finding the row for col 3
while(1) { {
C1=C2=C3=C4=1; if(R1==0)
C1=0; P1=0xAB; //3
rowfind1(); if(R2==0)
C1=1;C2=0; P1=0xEE; //6
rowfind2(); if(R3==0)
C2=1;C3=0; P1=0xAF; //9
rowfind3(); }
C3=1; C4=0; void rowfind4() // finding the row for col 4
rowfind4(); {
C4=1; } if(R1==0)
} P1=0x6F; //A
void rowfind1() // finding the row for col 1 if(R2==0)
{ P1=0xEF; //B
if(R1==0) if(R3==0)
P1=0x21; //1 P1=0xC6; //C
if(R2==0) if(R4==0)
P1=0x2D; //4 P1=0xE7; //D
if(R3==0) }

70
Chapter 9

Actuator interfacing & programming


An actuator is the mechanism by which a control system acts upon an environment. The control
system can be simple (a fixed mechanical or electronic system), software-based (e.g. a printer
driver, robot control system), a human, or any other input. In context of embedded system, an
actuator can be output device or component which can be used to see the response of the whole
system. Examples of actuators in embedded system are LED, LCD, Relay, Motor etc

9.1 Buzzer

A buzzer or beeper is an audio signaling device, which may be mechanical, electromechanical,


or piezoelectric. Typical uses of buzzers and beepers include alarm devices, timers, and
confirmation of user input such as a mouse click or keystroke.

Type of buzzers

Electromechanical
Early devices were based on an electromechanical system identical to an electric bell without the
metal gong. Similarly, a relay may be connected to interrupt its own actuating current, causing the
contacts to buzz. Often these units were anchored to a wall or ceiling to use it as a sounding board.
The word "buzzer" comes from the rasping noise that electromechanical buzzers made.

Mechanical
A joy buzzer is an example of a purely mechanical buzzer. They require drivers.

Piezoelectric
A piezoelectric element may be driven by an oscillating electronic circuit or other audio signal
source, driven with a piezoelectric audio amplifier. Sounds commonly used to indicate that a
button has been pressed are a click, a ring or a beep.

(a) (b) (c)

Fig 9.1: Types of buzzers (a) Electromechanical (b) Mechanical (c) Piezoelectric

9.1.1 Interfacing buzzer and control the buzzer with push button

71
Interfacing diagram:

Program:

Assembly Embedded C
PB EQU P3.5 #include<reg51.h>
BUZZER EQU P2.0 int i,j;
ORG 00H sbit buzzer=P2^0;
SETB PB;Push Button as input sbit push=P3^5;
CHECK: void main(){
JNB PB, Buzzer_ON ;if Push Button while(1) //infinite loop
not pressed {
SETB BUZZER ;turn OFF Buzzer if(push==0) //if value in
AJMP CHECK push is 0
Buzzer_ON: CLR BUZZER ;else turn ON buzzer=0; //BUZZER ON
Buzzer else
AJMP CHECK buzzer=1; ??BUZZER OFF
END }
}

9.2 RELAY: A relay is an electrically operated switch. Many relays use an electromagnet to
mechanically operate a switch, but other operating principles are also used, such as solid-state relays.
Relays are used where it is necessary to control a circuit by a separate low-power signal, or where several
circuits must be controlled by one signal.

9.2.1 WAP to turn on the fan using when there is motion in the room

Interfacing diagram:

72
Program:

Assembly Embedded C
;Program: 12.4.1.1.WAP to turn on the fan using #include<reg51.h>
when there is motion in the room sbit PIR=P1^0;
RELAY_FAN EQU P2.0 sbit RELAY_FAN=P2^0;
PIR EQU P2.1 void main(){
ORG 00H while(1) //infinite loop
SETB PIR ;PIR as input {
CHECK: if(PIR==1) //check PIR
JNB PIR, Fan_OFF ;if motion {
detected RELAY_FAN=0; //FAN ON
CLR RELAY_FAN ;turn ON Fan }
AJMP CHECK else
Fan_OFF: SETB RELAY_FAN ;else RELAY_FAN=1; //FAN OFF
turn OFF Fan }
AJMP CHECK }
END

9.2.2 WAP to turn on the high intensity bulb when there is not enough light and turn on low
intensity bulb when there is some amount of light present in the room

Interfacing diagram:

Program:

Assembly Embedded C
RELAY_BULB EQU P2.0 #include<reg51.h>
LDR EQU P2.1 sbit LDR=P2^1;
ORG 00H sbit RELAY_BULB1=P2^0;
SETB LDR ;LDR as input sbit RELAY_BULB2=P2^2;
CHECK: void main(){
JNB LDR,Bulb2_ON ;if light intensity is low while(1) {
SETB RELAY_BULB ;turn ON Bulb 1 if(LDR==1) //check LDR
AJMP CHECK {
Bulb2_ON: CLR RELAY_BULB ; else RELAY_BULB1=0; //bulb1 ON
turn on Bulb 2 RELAY_BULB2=1; //bulb2 OFF
AJMP CHECK }
END else
RELAY_BULB2=0; // bulb2 ON
RELAY_BULB1=1; //bulb1 OFF
}
}

73
9.3 DC motor

A DC motor is any of a class of rotary electrical machines that converts direct current electrical
energy into mechanical energy. The most common types rely on the forces produced by magnetic
fields. Nearly all types of DC motors have some internal mechanism, either electromechanical or
electronic, to periodically change the direction of current flow in part of the motor.

Principle:

In any electric motor, operation is based on simple electromagnetism. A current-carrying conductor


generates a magnetic field; when this is then placed in an external magnetic field, it will experience
a force proportional to the current in the conductor, and to the strength of the external magnetic field.
As you are well aware of from playing with magnets as a kid, opposite (North and South) polarities
attract, while like polarities (North and North, South and South) repel. The internal configuration of
a DC motor is designed to harness the magnetic interaction between a current-carrying conductor
and an external magnetic field to generate rotational motion.

9.3.1 WAP to change the direction of rotation of DC Motor

Interfacing diagram:

Program:

Assembly
;Program: Direction of rotation of DC motor Motor_CW: SETB M1 ;clockwise
PB_CW EQU P3.2 rotation
PB_CCW EQU P3.5 CLR M0
M0 EQU P2.0 AJMP CHECK_KB
M1 EQU P2.1 Motor_CCW: CLR M1 ;counter clockwise
ORG 00H rotation
SETB PB_CW ;make push buttons SETB M0
pins as input AJMP CHECK_KB
SETB PB_CCW END
CHECK_KB: JNB PB_CW, Motor_CW ;jump
for clockwise
JNB PB_CCW, Motor_CCW ;jump
for counter clockwise
SETB M1 ;else stop motor
SETB M0
AJMP CHECK_KB

74
Embedded C
#include<reg51.h> If (BACKWARD==0){
sbit FORWARD=P3^2; MOTOR1=0;
sbit BACKWARD=P3^5; MOTOR2=1;
sbit MOTOR1=P2^0; }
sbit MOTOR2=P2^1; else{
void main(){ MOTOR1=0;
while(1) { MOTOR2=0;
if(FORWARD==0) //if value of push is 0 }
{ }
MOTOR1=0; }
MOTOR2=1; }

9.3.2 WAP to control the Robotic car motion (forward, backward, left, right) using DC motor

Interfacing diagram:

Program:

Assembly
PB_F EQU P3.2 JNB PB_L, Motor_LT ;jump left motion
PB_B EQU P3.3 JNB PB_R, Motor_RT ;jump right motion
PB_L EQU P3.4 MOV Motor, #11111111B ;else stop motor
PB_R EQU P3.5 AJMP CHECK_KB
Motor EQU P2 ;P2.3-P2.0 Motor_FW: MOV Motor, #11111010B
ORG 00H ;forward
SETB PB_F ;make push buttons AJMP CHECK_KB
pins as input Motor_BW: MOV Motor, #11110101B
SETB PB_B ;backward
SETB PB_L AJMP CHECK_KB
SETB PB_R Motor_LT: MOV Motor, #11110110B ;left
CHECK_KB: JNB PB_F, Motor_FW AJMP CHECK_KB
;PB_F=0, jump for forward motion Motor_RT: MOV Motor, #11111001B
JNB PB_B, Motor_BW ;jump for ;right
backward motion AJMP CHECK_KB
END

75
Embedded C
#include<reg51.h> If (LEFT==0){
# define Motor P2 Motor=0xF5;
sbit FORWARD=P3^2; delay(1000);
sbit BACKWARD=P3^3; Motor=0x00;
sbit LEFT=P3^4; Delay(1000);
sbit RIGHT=P3^5; }
void delay(); If (RIGHT==0){
void main(){ Motor=0xF9;
while(1) { delay(1000);
If ( FORWARD==0){ Motor=0x00;
Motor=0xFA; Delay(1000);
delay(1000); }
Motor=0x00; else
delay(1000); Motor=0x00;
} }
If (BACKWARD==0){ }
Motor=0xF5; void delay(){
delay(1000); int i,j;
Motor=0x00; for(i=0;i<1000;i++)
Delay(1000); for(j=0;j<50;j++);
} }

9.3.3 WAP to change the speed of the Robotic car (DC motor) using PWM

Interfacing diagram:

Program:

Assembly Embedded C
;Program: DC motor speed control using PWM //Program: Speed of DC motor
PB_25 EQU P3.2 #include<reg51.h>
PB_50 EQU P3.5 sbit PB_25=P3^2;
PB_75 EQU P3.6 sbit PB_50=P3^5;
PB_100 EQU P3.7 sbit PB_75=P3^6;
M1 EQU P2.1 sbit PB_100=P3^7;
M0 EQU P2.0 sbit M1=P2^1;

76
ORG 00H sbit M0=P2^0;
SETB PB_25 ;make push buttons pins void main(){
as input int count;
SETB PB_50 PB_25=1; PB_50=1;
SETB PB_75 PB_75=1;PB_100=1;//make push
SETB PB_100 buttons pins as input
SETB M1 ;initially motor stopped M1=1; M0=1; //motor stopped initially
SETB M0 while(1){
CHECK_KB: JNB PB_25, PWM_25 ;jump if(PB_25==0){ //pwm duty cycle 25
for 25% duty cycle M0=0;
JNB PB_50, PWM_50 ;jump for 50% for(count=0;count<25;count++);
duty cycle M0=1;
JNB PB_75, PWM_75 ;jump for 75% for(count=0;count<75;count++);
duty cycle }
JNB PB_100, PWM_100 ;jump for 100% else if(PB_50==0){//pwm duty cycle 50
duty cycle M0=0;
SETB M0 ;else stop motor for(count=0;count<50;count++);
AJMP CHECK_KB M0=1;
PWM_25: CLR M0 ;25% duty cycle for(count=0;count<50;count++);
MOV R0,#25 ;Motor ON for 25 count }
HERE25: DJNZ R0,HERE25 else if(PB_75==0){//pwm duty cycle 75
SETB M0 M0=0;
MOV R0,#75 ;Motor OFF for 75 count for(count=0;count<75;count++);
HERE_25: DJNZ R0,HERE_25 M0=1;
AJMP CHECK_KB for(count=0;count<25;count++);
PWM_50: CLR M0 ;50% duty cycle }
MOV R0,#50 ;Motor ON for 50 count else if(PB_100==0){//pwm duty cycle 100
HERE50: DJNZ R0,HERE50 M0=0;
SETB M0 for(count=0;count<100;count++);
MOV R0,#50 ;Motor OFF for 50 count }
HERE_50: DJNZ R0,HERE_50 else //no motion
AJMP CHECK_KB M0=1;
PWM_75: CLR M0 ;75% duty cycle }
MOV R0,#75 ;Motor ON for 75 count }
HERE75: DJNZ R0,HERE75
SETB M0
MOV R0,#25 ;Motor OFF for 25 count
HERE_75: DJNZ R0,HERE_75
AJMP CHECK_KB
PWM_100: CLR M0 ;100% duty cycle
MOV R0,#100 ;Motor ON for 100 count
HERE100: DJNZ R0,HERE100
AJMP CHECK_KB
END

77
10.1 Stepper motor

A stepper motor or step motor or stepping motor is a brushless DC electric motor that divides a full
rotation into a number of equal steps. The motor's position can then be commanded to move and hold
at one of these steps without any feedback sensor (an open-loop controller), as long as the motor is
carefully sized to the application in respect to torque and speed.

Two-phase stepper motors

There are two basic winding arrangements for the electromagnetic coils in a two phase stepper
motor: bipolar and unipolar.

(A) Unipolar Motor


A unipolar stepper motor has one winding with center tap per phase. Each section of windings
is switched on for each direction of magnetic field. Since in this arrangement a magnetic pole
can be reversed without switching the direction of current, the commutation circuit can be made
very simple (e.g., a single transistor) for each winding. Typically, given a phase, the center tap
of each winding is made common: giving three leads per phase and six leads for a typical two
phase motor. Often, these two phase commons are internally joined, so the motor has only five
leads.
(B) Bipolar Motor
Bipolar motors have a single winding per phase. The current in a winding needs to be reversed
in order to reverse a magnetic pole, so the driving circuit must be more complicated, typically
with an H-bridge arrangement (however there are several off-the-shelf driver chips available
to make this a simple affair). There are two leads per phase, none are common.

9.3.4 WAP to rotate the unipolar stepper motor continuously using single coil 4 steps
sequence

Interfacing diagram:

78
Program:

Assembly Embedded C
;Program: Rotate unipolar stepper motor using //Program: Rotate unipolar stepper motor using
single coil 4 steps single coil 4 steps
Stepper EQU P2 ;P2.3-P2.0 #include<reg51.h>
ORG 00H sfr stepper=0xA0; //P2.3-P2.0
MOV A,#01110111B ;initial value for void delay();
stepper
MAIN: void main(){
MOV Stepper,A unsigned char step=0x77;
RR A ;Rotate for next step while(1){
ACALL DELAY stepper=step;
AJMP MAIN step=step>>1|step<<7;
delay();
DELAY: ;Function for delay }
MOV R1, #200 }
LOOP1: MOV R2, #200
LOOP: DJNZ R2, LOOP void delay(){
DJNZ R1, LOOP1 unsigned int val;
RET for(val=0;val<40000;val++);
END }

9.3.5 WAP to rotate the unipolar stepper motor continuously using double coil 4 steps
sequence

Program:

Assembly Embedded C
;Program: Rotate unipolar stepper motor using //Program: Rotate unipolar stepper motor using
double coil 4 steps double coil 4 steps
Stepper EQU P2 ;P2.3-P2.0 #include<reg51.h>
ORG 00H sfr stepper=0xA0; //P2.3-P2.0
MOV A,#00110011B ;initial value for void delay();
stepper
MAIN: void main(){
MOV Stepper,A unsigned char step=0x33;
RR A ;Rotate for next step while(1){
ACALL DELAY stepper=step;
AJMP MAIN step=step>>1|step<<7; //rotate right
delay();
DELAY: ;Function for delay }
MOV R1, #200 }
LOOP1: MOV R2, #200
LOOP: DJNZ R2, LOOP void delay(){
DJNZ R1, LOOP1 unsigned int val;
RET for(val=0;val<40000;val++);
END }

79
9.2.1 WAP to rotate the unipolar stepper motor continuously using 8 steps sequence

Program:

Assembly Embedded C
;Program: Rotate unipolar stepper motor using 8 //Program: Rotate unipolar stepper motor using
steps 8 steps
Stepper EQU P2 ;P2.3-P2.0 #include<reg51.h>
ORG 00H sfr stepper=0xA0; //P2.3-P2.0
MAIN: void delay();
MOV Stepper,#11110111B ;values
for stepper void main(){
ACALL DELAY while(1){
MOV Stepper,#11110011B stepper=0xF7;
ACALL DELAY delay();
MOV Stepper,#11111011B stepper=0xF3;
ACALL DELAY delay();
MOV Stepper,#11111001B stepper=0xFB;
ACALL DELAY delay();
MOV Stepper,#11111101B stepper=0xF9;
ACALL DELAY delay();
MOV Stepper,#11111100B stepper=0xFD;
ACALL DELAY delay();
MOV Stepper,#11111110B stepper=0xFC;
ACALL DELAY delay();
MOV Stepper,#11110110B stepper=0xFE;
ACALL DELAY delay();
AJMP MAIN stepper=0xF6;
delay();
DELAY: ;Function for delay }
MOV R1, #200 }
LOOP1: MOV R2, #200
LOOP: DJNZ R2, LOOP void delay(){
DJNZ R1, LOOP1 unsigned int val;
RET for(val=0;val<40000;val++);
END }

80
9.2.2 WAP to control the direction of rotation of unipolar stepper motor according to the
push button pressed

Program:

Assembly Embedded C
;Program: Control direction of rotation of //Program: Control direction of rotation of
unipolar stepper motor using single coil 4 unipolar stepper motor using single coil 4
steps steps
Stepper EQU P2 ;P2.3-P2.0 #include<reg51.h>
PB_CW EQU P3.2 sfr stepper=0xA0; //P2.3-P2.0
PB_CCW EQU P3.5 sbit PB_CW=P3^2;
ORG 00H sbit PB_CCW=P3^5;
MOV A,#01110111B ;initial value void delay();
for stepper
MAIN: void main(){
JNB PB_CW,STEPPER_CW unsigned char step=0x77;
JNB PB_CCW,STEPPER_CCW while(1){
AJMP MAIN if(PB_CW==0){
STEPPER_CW: RR A ;Rotate for next step stepper=step;
MOV Stepper,A ;mov values for step=step>>1|step<<7;
stepper to Stepper delay();
ACALL DELAY }
AJMP MAIN else if(PB_CCW==0){
STEPPER_CCW: RL A ;Rotate for stepper=step;
next step step=step<<1|step>>7;
MOV Stepper,A ;mov values to delay();
Stepper }
ACALL DELAY }
AJMP MAIN }

DELAY: ;Function for delay void delay(){


MOV R1, #200 unsigned int val;
LOOP1: MOV R2, #200 for(val=0;val<40000;val++);
LOOP: DJNZ R2, LOOP }
DJNZ R1, LOOP1
RET
END

81
9.2.3 WAP to rotate the bipolar stepper motor continuously using single coil 4 steps
sequence

Interfacing diagram:

Program:

Assembly Embedded C
;Program: Rotate bipolar stepper motor using //Program: Rotate bipolar stepper motor using
single coil 4 steps single coil 4 steps
Stepper EQU P2 ;P2.3-P2.0 #include<reg51.h>
ORG 00H sfr stepper=0xA0; //P2.3-P2.0
MAIN: void delay();
MOV Stepper,#11111011B ;steps
for bipolar stepper void main(){
ACALL DELAY while(1){
MOV Stepper,#11111110B stepper=0xFB;//steps for bipolar stepper
ACALL DELAY delay();
MOV Stepper,#11110111B stepper=0xFE;
ACALL DELAY delay();
MOV Stepper,#11111101B stepper=0xF7;
ACALL DELAY delay();
AJMP MAIN stepper=0xFD;
delay();
DELAY: ;Function for delay }
MOV R1, #10 }
LOOP1: MOV R2, #200 void delay(){
LOOP: DJNZ R2, LOOP unsigned int val;
DJNZ R1, LOOP1 for(val=0;val<2000;val++);
RET }
END

82
9.2.4 WAP to rotate the bipolar stepper motor continuously using double coil 4 steps
sequence

Program:

Assembly Embedded C
;Program: Rotate bipolar stepper motor //Program: Rotate bipolar stepper motor
using double coil 4 steps using two coil 4 steps
Stepper EQU P2 ;P2.3-P2.0 #include<reg51.h>
ORG 00H sfr stepper=0xA0; //P2.3-P2.0
MAIN: void delay();
MOV Stepper,#11111010B ;steps void main()
for bipolar stepper {
ACALL DELAY while(1)
MOV Stepper,#11110110B {
ACALL DELAY stepper=0xFA;//steps for bipolar
MOV Stepper,#11110101B stepper
ACALL DELAY delay();
MOV Stepper,#11111001B stepper=0xF6;
ACALL DELAY delay();
AJMP MAIN stepper=0xF5;
delay();
DELAY: ;Function for delay stepper=0xF9;
MOV R1, #10 delay();
LOOP1: MOV R2, #200 }
LOOP: DJNZ R2, LOOP }
DJNZ R1, LOOP1 void delay()
RET {
END unsigned int val;
for(val=0;val<2000;val++);
}

83
9.2.5 WAP to rotate the bipolar stepper motor continuously using 8 steps sequence

Program:

Assembly Embedded C
;Program: Rotate bipolar stepper motor //Program: Rotate bipolar stepper motor
using 8 steps using single coil 8 steps
Stepper EQU P2 ;P2.3-P2.0 #include<reg51.h>
ORG 00H sfr stepper=0xA0; //P2.3-P2.0
MAIN: void delay();
MOV Stepper,#11111011B
;8 steps for bipolar stepper void main(){
ACALL DELAY while(1){
MOV Stepper,#11111010B stepper=0xFB;//steps for bipolar
ACALL DELAY stepper
MOV Stepper,#11111110B delay();
ACALL DELAY stepper=0xFA;//steps for bipolar
MOV Stepper,#11110110B stepper
ACALL DELAY delay();
MOV Stepper,#11110111B stepper=0xFE;
ACALL DELAY delay();
MOV Stepper,#11110101B stepper=0xF6;//steps for bipolar
ACALL DELAY stepper
MOV Stepper,#11111101B delay();
ACALL DELAY stepper=0xF7;
MOV Stepper,#11111001B delay();
ACALL DELAY stepper=0xF5;//steps for bipolar
AJMP MAIN stepper
delay();
DELAY: ;Function for delay stepper=0xFD;
MOV R1, #5 delay();
LOOP1: MOV R2, #200 stepper=0xF9;//steps for bipolar
LOOP: DJNZ R2, LOOP stepper
DJNZ R1, LOOP1 delay();
RET }
END }

void delay(){
unsigned int val;
for(val=0;val<2000;val++);
}

84
9.2.6 WAP to control the direction of rotation of bipolar stepper motor according to the
push button pressed

Program:

Assembly Embedded C
;Program: Control direction of rotation of bipolar //Program: Rotate bipolar stepper motor using
stepper motor using single coil 4 steps single coil 4 steps
Stepper EQU P2 ;P2.3-P2.0 #include<reg51.h>
PB_CW EQU P3.2 sfr stepper=0xA0; //P2.3-P2.0
PB_CCW EQU P3.5 sbit PB_CW=P3^2;
ORG 00H sbit PB_CCW=P3^5;
MAIN: void delay();
JNB PB_CW,STEPPER_CW
JNB PB_CCW,STEPPER_CCW void main(){
AJMP MAIN while(1){
STEPPER_CW: MOV Stepper,#11111011B if(PB_CW==0){
;steps for bipolar stepper CW stepper=0xFB;//steps for bipolar stepper CW
ACALL DELAY delay();
MOV Stepper,#11111110B stepper=0xFE;
ACALL DELAY delay();
MOV Stepper,#11110111B stepper=0xF7;
ACALL DELAY delay();
MOV Stepper,#11111101B stepper=0xFD;
ACALL DELAY delay();
AJMP MAIN }
STEPPER_CCW: MOV Stepper,#11111101B else if(PB_CCW==0){
;steps for bipolar stepper CCW stepper=0xFD;//steps for bipolar stepper
ACALL DELAY delay();
MOV Stepper,#11110111B stepper=0xF7;
ACALL DELAY delay();
MOV Stepper,#11111110B stepper=0xFE;
ACALL DELAY delay();
MOV Stepper,#11111011B stepper=0xFB;
ACALL DELAY delay();
AJMP MAIN }
}
DELAY: ;Function for delay }
MOV R1, #10
LOOP1: MOV R2, #200 void delay(){
LOOP: DJNZ R2, LOOP unsigned int val;
DJNZ R1, LOOP1 for(val=0;val<2000;val++);
RET }
END

85
9.4 Dc fan
A fan is a machine used to create flow within a fluid, typically a gas such as air. The fan consists of a
rotating arrangement of vanes or blades which act on the fluid. The rotating assembly of blades and
hub is known as an impeller, a rotor, or a runner. Usually, it is contained within some form of housing
or case. This may direct the airflow or increase safety by preventing objects from contacting the fan
blades. Most fans are powered by electric motors, but other sources of power may be used,
including hydraulic motors and internal combustion engines.

9.4.1 WAP to turn on DC fan when switch is pressed

Interfacing diagram:

Program:

Assembly Embedded C
PB EQU P3.5 #include<reg51.h>
FAN EQU P2.0 sbit PB=P3^5;
ORG 00H sbit FAN=P2^0;
SETB PB;Push Button as input void main(){
CHECK: PB=1; //Push Button as input
JNB PB, FAN_ON ;if Button not while(1){
pressed, if(PB) //if Button not pressed,
CLR FAN ;turn off DC Fan FAN=0; //turn off DC Fan
AJMP CHECK else
FAN_ON: SETB FAN ;else turn on DC FAN=1; //if button pressed, turn on Fan
Fan }
AJMP CHECK }
END

86
Chapter 10
Timer & Counter

Timer is a clock that controls the sequence of an event while counting in fixed intervals of
time. A Timer is used for producing precise time delay. Secondly, it can be used to repeat or
initiate an action after/at a known period of time. The 8051 has two timers/counters.

They can be used either as

• Timers to generate a time delay

• Event counters to count events happening outside the microcontroller

10.1 Timer

Timer 0 and 1 are 16-bit wide

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

Both timers 0 and 1 use the same register, called TMOD (timer mode), to set the various
timer operation modes. TMOD is an 8-bit register

• The lower 4 bits are for Timer 0

• The upper 4 bits are for Timer 1

The lower four bits (TMOD.0 – TMOD.3) are used to configure Timer 0 while the higher four
bits (TMOD.4 – TMOD.7) are for Timer 1. When GATE is high, the corresponding Timer is
enabled only when there is an interrupt at corresponding INTx pin of AT89C51 controller and
Timer control bit is high. Otherwise only setting Timer control bit is sufficient to start the
Timer.

If C/T is low, Timer is used for time keeping, i.e., Timer updates its value automatically
corresponding to 8051 clock source. When C/T is high, Timer is used as counter, i.e., it updates
its value when it receives pulse from outside the 8051 controller.

M1 and M0 bits decide the Timer modes. There are four Timer modes designated as Modes 0,
1, 2 and 3.

87
Modes 1 and 2 are most commonly used while working with Timers.
TMOD = 0x01; sets the mode1 of Timer0 used for timing
TMOD = 0x20; sets the mode2 of Timer1 used for timing

Operation
The registers of Timers are loaded with some initial value. The value of a Timer register
increases by one after every machine cycle. One machine cycle duration is the 1/12th of the
frequency of the crystal attached to the controller.

For example, if the frequency of the crystal is 12 MHz, then the frequency for Timer will be
1MHz (1/12 of crystal frequency) and hence the time (T = 1/f) taken by the Timer to count by
one is 1µs (1/1MHz). Similarly if an 11.0592 MHz crystal is used, operating frequency of
Timer is 921.6 KHz and the time period is 1.085 µs.
If no value is loaded into the Timer, it starts counting from 0000H.

When the Timer reaches FFFFH, it reloads to 0000H. This roll over is communicated to the
controller by raising a flag corresponding to that Timer, i.e., a flag bit is raised (set high) when
the timer starts counting from 0000H again. TF0 and TF1 are the Timer flags corresponding
to Timers 0 and 1. These flags must be cleared (set low) by software every time they are raised.
The Timer may terminate updating register values after a roll over or continue with its
operation.

For every Timer, there is a corresponding Timer control bit which can be set or cleared by the
program to start or stop the Timer. TR0 and TR1 are the control bits for Timers 0 and 1
respectively. Setting the control bit would start the Timer.
TR0 = 1; starts Timer 0
TR1 = 1; starts Timer 1
Clearing the control bit would stop the Timer.
TR0 = 0; stops Timer 0
TR1 = 0; stops Timer1

88
10.1.1 Timer 0, Mode 0 – LED blink with 1 s delay using Timer0 mode 0

Interfacing Diagram:

Program

Assembly Embedded C
;Program: LED blink with 1 s delay using Timer0 //led blink with 1s delay using timer 0 mode 0
mode 0 #include<reg51.h>
LED EQU P1.0 sbit led=P1^0;
ORG 00H void delay(void);
MOV TMOD,#00H ;Timer 0, mode void main(){
0(13-bit mode) int i;
MAIN: while(1){
CPL LED ;LED=OFF led=0;//ON
MOV R7,#112 ;actual value=115 for(i=0;i<1000;i++)
TIMES_112: ACALL DELAY_TIMER ;1 S delay();
Delay led=1;//OFF
DJNZ R7,TIMES_112 for(i=0;i<1000;i++)
SJMP MAIN delay();
}
DELAY_TIMER: }
MOV TL0,#0C0H void delay() //1ms delay
MOV TH0,#00H {
SETB TR0 ;start the timer 0 TMOD=0x00; //timer 0,mode 0
AGAIN: JNB TF0,AGAIN ;check for timer TL0=0x68;
completion TH0=0xFC;
CLR TR0;stop timer 0 TR0=1; //start timer 0
CLR TF0 ;clear timer 0 flag while(TF0==0); //wait for overflow
RET TR0=0;
END TF0=0;
}

89
10.1.2 Timer 0, Mode 1 – LED 2s ON, 1s OFF

Interfacing Diagram:

Program

Assembly Embedded C
;Program: LED 2s ON 1s OFF using Timer0 mode //led 2s ON, 1s OFF in timer 0 mode 1
1 #include<reg51.h>
LED EQU P1.0 sbit led=P1^0;
ORG 00H void delay(void);
MOV TMOD,#01H void main(){
;Timer 0, mode 1(16-bit mode) int i;
MAIN: while(1)
CLR LED ;LED=OFF {
MOV R7,#14 led=0; //ON
TIMES_28: ACALL DELAY_TIMER ;2 S for(i=0;i<1000;i++)
Delay delay();
DJNZ R7,TIMES_28 led=1; //OFF
SETB LED for(i=0;i<2000;i++)
;LED=ON delay();
MOV R7,#14 }
TIMES_14: ACALL DELAY_TIMER ;1 S }
Delay void delay() //1ms delay
DJNZ R7,TIMES_14 {
SJMP MAIN TMOD=0x01; //timer 0,mode 1
TL0=0x68;
DELAY_TIMER: TH0=0xFC;
MOV TL0,#18H TR0=1; //start timer 0
MOV TH0,#02H while(TF0==0); //wait for overflow
SETB TR0 ;start the timer 0 TR0=0;
AGAIN: JNB TF0,AGAIN ;check for timer TF0=0;
completion }
CLR TR0;stop timer 0
CLR TF0 ;clear timer 0 flag
RET
END

90
10.1.1 Timer 0, Mode 2 – LED 1s square wave

Interfacing Diagram:

Program:

Assembly Embedded C
;Program: 1s square wave Timer 0, Mode 2 //Timer 0, Mode 2 – LED 1s square wave
LED EQU P1.0 #include<reg51.h>
ORG 00H sbit led=P1^0;
MOV TMOD,#02H;Timer 0, mode 2(8-bit void delay(void);
mode) void main()
MOV TH0,#06H ;TH0=06H {
SETB TR0 ;start the timer 0 int i;
MAIN: while(1){
CPL LED led=0; //ON
MOV R6,#61 ;61*60=3660 for(i=0;i<1000;i++)
actual=3686 delay();
TIMES_61: MOV R7,#60 ;1 S Delay led=1; //OFF
TIMES_60: JNB TF0,TIMES_60 ;check for(i=0;i<1000;i++)
for timer completion delay();
CLR TF0 ;clear timer 0 flag }
DJNZ R7,TIMES_60 }
DJNZ R6,TIMES_61 void delay(){
SJMP MAIN TMOD=0x02; //timer 0,mode 2
END TL0=0x68;
TH0=0xFC;
TR0=1; //start timer 0
while(TF0==0); //wait for overflow
TR0=0;
TF0=0;
}

91
10.1.2 Timer 1, Mode 0 – LED blink 1s (Push button pressed)

Interfacing Diagram:

Program:

Assembly Embedded C
LED EQU P1.0 #include<reg51.h>
PB EQU P3.5 sbit led=P1^0;
ORG 00H sbit push=P3^5;
MOV TMOD,#00H void delay(void);
;Timer 0, mode 0(13-bit mode) void main(){
MAIN: int i;
JB PB,MAIN while(1){
CPL LED if(push==0)
MOV R7,#112 {
TIMES_112: ACALL DELAY_TIMER ;1 S led=0; //ON
Delay for(i=0;i<1000;i++)
DJNZ R7,TIMES_112 delay();
SJMP HERE led=1; //OFF
for(i=0;i<1000;i++)
DELAY_TIMER: delay();
MOV TL1,#0C0H }
MOV TH1,#00H }
SETB TR1 ;start the timer }
AGAIN: JNB TF1,AGAIN ;check for timer void delay(){
completion TMOD=0x00; //timer 1,mode 0
CLR TR1;stop timer TL1=0x68;
CLR TF1 ;clear timer flag TH1=0xFC;
RET TR1=1; //start timer 1
END while(TF1==0); //wait for overflow
TR1=0;
TF1=0;
}

92
10.1.3 Timer 1, Mode 1 – LED blink 2s (Push button pressed), LED blink 0.5s (Push button not
pressed)

Interfacing Diagram:

Assembly Embedded C
LED EQU P1.0 #include<reg51.h>
PB EQU P3.5 sbit led=P3^4;
ORG 00H sbit push=P3^5;
MOV TMOD,#10H ;Timer 1, mode void delay(void);
1(16-bit mode) void main(){
MIAN: int i;
CPL LED while(1){
JNB PB,DELAY_2S if(push==0){
MOV R7,#7 led=0; //ON
TIMES_7: ACALL DELAY_TIMER ;0.5 S for(i=0;i<2000;i++)
Delay delay();
DJNZ R7,TIMES_7 led=1; //OFF
SJMP HERE for(i=0;i<2000;i++)
DELAY_2S: MOV R7,#28 delay(); }
TIMES_28: ACALL DELAY_TIMER ;2 S else{
Delay led=0; //ON
DJNZ R7,TIMES_28 for(i=0;i<500;i++)
SJMP HERE delay();
led=1; //OFF
DELAY_TIMER: for(i=0;i<500;i++)
MOV TL1,#18H delay();
MOV TH1,#02H } } }
SETB TR1 ;start the timer 1 void delay(){
AGAIN: JNB TF1,AGAIN ;check for timer TMOD=0x10; //timer 1,mode 1
completion TL1=0x68;
CLR TR1;stop timer 1 TH1=0xFC;
CLR TF1 ;clear timer 1 flag TR1=1; //start timer 1
RET while(TF1==0); //wait for overflow
END TR1=0; TF1=0; }

93
10.1.4 Timer 1, Mode 2 – LED 1 blink 1s (Push button pressed), LED 2 blink 1s (Push button not
pressed)

Interfacing Diagram:

Assembly Embedded C
LED1 EQU P1.0 #include<reg51.h>
LED2 EQU P1.1 sbit led1=P1^0;
PB EQU P3.5 sbit led2=P1^1;
ORG 00H sbit push=P3^5;
MOV TMOD,#02H ;Timer 0, mode void delay(void);
2(8-bit mode) void main(){
MOV TH0,#06H ;TH0=06H, the high byte int i;
SETB TR0 ;start the timer 0 while(1){
MAIN: if(push==0){
JB PB,LED_2 led1=0; //ON
CPL LED1 for(i=0;i<1000;i++)
SJMP DELAY delay();
LED_2: CPL LED2 led1=1; //OFF
DELAY: MOV R6,#61 for(i=0;i<1000;i++)
TIMES_61: MOV R7,#60 ;1 S Delay delay();
TIMES_60: JNB TF0,TIMES_60 ;check }
for timer completion else{
CLR TF0 ;clear timer 0 flag led2=0; //ON
DJNZ R7,TIMES_60 for(i=0;i<1000;i++)
DJNZ R6,TIMES_61 delay();
SJMP MAIN led2=1; //OFF
END for(i=0;i<1000;i++)
delay();
}
}
}
1ms delay function

94
10.2 Counter
10.2.1 Count the number of persons crossing using IR sensor connected at P3.5 (counter 1, mode
1) and display on LCD

Interfacing Diagram:

Assembly Embedded C
;Program: Count the number of persons crossing //Count the number of persons crossing using IR
using IR sensor connected at P3.5 (counter 1, sensor connected at P3.5 (counter 1, mode 1)
mode 1) and display on LCD and display on LCD
E EQU P2.7 #include<reg51.h>
RS EQU P2.6 sbit sensor=P3^5;
LCD EQU P0 sbit RS=P2^6;
ORG 00H sbit EN=P2^7;
MOV TMOD,#50H ;counter 1, unsigned char a[3];
mode 1 int bytes;
MOV TL1,#00H void cmd(unsigned char cmd); //to send
MOV TH1,#00H command
SETB TR1 ;enable counter 1 void cmdlcd(unsigned char cmd); //to send data
MAIN: void delay(); //to cause some delay
ACALL LCD_INIT void main()
AGAIN: MOV R4, #80H {
ACALL LCD_COMMAND TMOD=0x54; //counter 1 in mode 1
MOV A,TL1 ;convert counter value TH1=0; //cause max delay
to ASCII TL1=0;
MOV B,#10 ;display on LCD TR1=1; //start counter 1

95
DIV AB while(1)
MOV R3,B {
MOV B,#10 cmd(0x38); delay(); //initialising LCD
DIV AB cmd(0x0E); delay(); //display ON,
ADD A,#30H cursor ON
MOV R4, A cmd(0x01); delay(); //clear display
ACALL LCD_DATA screen
MOV A,B cmd(0x80); delay(); //cursor on line 1
ADD A,#30H ,location1
MOV R4, A a[0]=TL1%10;
ACALL LCD_DATA a[1]=(TL1/10)%10;
MOV A,R3 a[2]=TL1/100;
ADD A,#30H for(bytes=3;bytes>0;bytes--)
MOV R4, A cmdlcd(a[bytes-
ACALL LCD_DATA 1]+0x30);
AJMP AGAIN }
LCD_INIT: }
CLR E
CLR RS //to send command
MOV R4, #38H ;Use 2 lines and 5×7 void cmd(unsigned char cmd)
matrix for LCD {
ACALL LCD_COMMAND P0=cmd;
ACALL DELAY RS=0; //for command
MOV R4, #0CH ;LCD ON, Cursor OFF //RW=0; //for write
ACALL LCD_COMMAND EN=1; //to enable
ACALL DELAY delay();
MOV R4, #01H ;LCD clear EN=0; //disable
ACALL LCD_COMMAND }
ACALL DELAY //to send data
RET void cmdlcd(unsigned char cmd
LCD_COMMAND: ;Function for LCD )
command {
CLR RS P0=cmd;
MOV LCD, R4 RS=1; //send data
SETB E //RW=0; //write
ACALL DELAY EN=1;
CLR E delay();
RET EN=0;
LCD_DATA: ;Function for LCD data }
SETB RS //to cause some delay
MOV LCD, R4 void delay()

96
SETB E {
ACALL DELAY int i,j;
CLR E for(i=0;i<1000;i++)
RET for(j=0;j<10;j++);
DELAY: ;Function for delay }
MOV R7, #200
LOOP1: MOV R6, #200
LOOP: DJNZ R6, LOOP
DJNZ R7, LOOP1
RET
END

10.2.2 Count the number of times the switch is pressed at P1.0 (counter 2) and display on LCD

Interfacing Diagram:

Assembly Embedded C
;Program: Count the number of times the switch //Count the number of times the switch is
is pressed at P1.0 (counter 2) and display on LCD pressed at P1.0 (counter 2) and display on LCD
E EQU P2.7 #include<reg52.h>
RS EQU P2.6 sbit push=P1^0;
LCD EQU P0 sbit RS=P2^6;
RCAP2L EQU 0CAH sbit EN=P2^7;
RCAP2H EQU 0CBH unsigned char a[3];
TL2 EQU 0CCH int bytes;
TH2 EQU 0CDH void cmd(unsigned char cmd); //to send
TR2 EQU 0CAH command

97
TF2 EQU 0CFH void cmdlcd(unsigned char cmd); //to send data
CP_RL2 EQU 0C8H void delay(); //to cause some delay
C_T2 EQU 0C9H void main()
EXEN2 EQU 0CBH {
EXF2 EQU 0CEH T2CON=0x02; //counter 2 000000010
ORG 00H TH2=0; //cause max delay
ACALL LCD_INIT TL2=0;
MOV TL2,#00H TR2=1; //start counter 2
MOV TH2,#00H while(1)
SETB C_T2 ;counter 2 {
SETB TR2 ;enable counter 2 cmd(0x38); delay(); //initialising LCD
AGAIN: cmd(0x0E); delay(); //display ON,
MOV A,TL2 ;convert counter value cursor ON
to ASCII cmd(0x01); delay(); //clear display
MOV B,#10 ;and display on LCD screen
DIV AB cmd(0x80); delay(); //cursor on line 1
MOV R3,B ,location1
MOV B,#10 a[0]=TL2%10;
DIV AB a[1]=(TL2/10)%10;
ADD A,#30H a[2]=TL2/100;
MOV R4, A for(bytes=3;bytes>0;bytes--)
ACALL LCD_DATA cmdlcd(a[bytes-
MOV A,B 1]+0x30);
ADD A,#30H }
MOV R4, A }
ACALL LCD_DATA
MOV A,R3 //to send command
ADD A,#30H void cmd(unsigned char cmd)
MOV R4, A {
ACALL LCD_DATA P0=cmd;
AJMP AGAIN RS=0; //for command
//RW=0; //for write
LCD_INIT: EN=1; //to enable
CLR E delay();
CLR RS EN=0; //disable
MOV R4, #38H ;Use 2 }
lines and 5×7 matrix for LCD //to send data
ACALL LCD_COMMAND void cmdlcd(unsigned char cmd
ACALL DELAY )
MOV R4, #0CH ;LCD {
ON, Cursor OFF P0=cmd;

98
ACALL LCD_COMMAND RS=1; //send data
ACALL DELAY //RW=0; //write
MOV R4, #01H ;LCD EN=1;
clear delay();
ACALL LCD_COMMAND EN=0;
ACALL DELAY }
RET //to cause some delay
void delay()
LCD_COMMAND: ;Function for LCD {
command int i,j;
CLR RS for(i=0;i<1000;i++)
MOV LCD, R4 for(j=0;j<10;j++);
SETB E }
ACALL DELAY
CLR E
RET

LCD_DATA: ;Function for LCD data


SETB RS
MOV LCD, R4
SETB E
ACALL DELAY
CLR E
RET

DELAY: ;Function for delay


MOV R7, #200
LOOP1: MOV R6, #200
LOOP: DJNZ R6, LOOP
DJNZ R7, LOOP1
RET
END

99
10.2.3 Count the number of times the switch is pressed at P3.4 (counter 0, mode 2) and if count
is greater than 10 than glow LED

Interfacing Diagram:

Assembly Embedded C
;Program:13.2.4. Count the number of //Count the number of times the switch is
times the switch is pressed at P3.4 (counter 0, pressed at P3.4 (counter 0, mode 2) and if count
mode 2) and if count is greater than 10 than is greater than 10 than glow LED
glow LED #include<reg51.h>
LED EQU P1.0 sbit led=P1^0;
ORG 00H void main()
MOV TMOD,#06H ;counter 0, {
mode 2 TMOD=0x46; //counter 0, mode 2
MOV TH0,#00H TL0=0; //cause max delay
SETB TR0 ;enable counter 0 TH0=0;
AGAIN: TR0=1; //start counter 0
MOV A,TL0 while(1)
CLR C {
SUBB A,#10 ;if counter value>10 if(TL0>10)
JC LED_OFF led=0;
CLR LED ;then LED ON else
AJMP AGAIN led=1;
LED_OFF: SETB LED ;else LED OFF }
AJMP AGAIN }
END

100
10.2.4 Count the number of times the switch is pressed at P3.5 (counter 1, mode 0) and if count is
even than glow LED

Interfacing Diagram:

Assembly Embedded C
;Program: Count the number of times the switch //Count the number of times the switch is
is pressed at P3.5 (counter 1, mode 0) and if pressed at P3.5 (counter 1, mode 0) and if count
count is even than glow LED is even than glow LED
LED EQU P1.0 #include<reg51.h>
ORG 00H sbit led=P1^0;
MOV TMOD,#40H ;counter 1, void main()
mode 0 {
MOV TH1,#00H int i;
MOV TL1,#00H TMOD=0x44; //counter 1,mode 0
SETB TR1 ;enable counter 1 TL1=0; //cause max delay
AGAIN: TH1=0;
MOV A,TL0 TR1=1; //start counter 1
MOV B,2 while(1)
DIV AB {
MOV A,B if(TL1%2==0)
JNZ LED_OFF ;if count=even led=0;
CLR LED ;then LED ON else
AJMP AGAIN led=1;
LED_OFF: SETB LED ;else LED OFF }
AJMP AGAIN }
END

101
10.2.5 Count the number of persons crossing using IR sensor connected at P1.0 (counter 2) and if
count is multiple of 5, make the buzzer sound connected at P1.7.

Interfacing Diagram:

Assembly Embedded C
;Program: 13.2.6. Count the number of //Count the number of persons crossing using IR
persons crossing using IR sensor connected at sensor connected at P1.0 (counter 2)
P1.0 (counter 2) and if count is multiple of 5, //and if count is multiple of 5, make the buzzer
make the buzzer sound connected sound connected at P1.7.
BUZZER EQU P2.0 #include<reg52.h>
RCAP2L EQU 0CAH sbit sensor=P1^0;
RCAP2H EQU 0CBH sbit buzzer=P1^7;
TL2 EQU 0CCH void main()
TH2 EQU 0CDH {
TR2 EQU 0CAH
TF2 EQU 0CFH T2CON=0x02; //counter 2 000000010
CP_RL2 EQU 0C8H TH2=0; //cause max delay
C_T2 EQU 0C9H TL2=0;
EXEN2 EQU 0CBH TR2=1; //start counter 2
EXF2 EQU 0CEH while(1)
ORG 00H {
MOV TL2,#00H if(TL2%5==0)
MOV TH2,#00H buzzer=0;
SETB C_T2 ;counter 2 else
SETB TR2 ;enable counter 2 buzzer=1;
AGAIN: }
MOV A,TL2 }
MOV B,#5 ;count divide by 5
DIV AB
MOV A,B

102
JNZ BUZZER_OFF ;if count is
multiple of 5
CLR BUZZER ;then buzzer ON
AJMP AGAIN
BUZZER_OFF: SETB BUZZER ;else buzzer OFF
AJMP AGAIN
END

10.2.6 Count the number of times the switch is pressed at P3.4 (counter 0, mode 2) and P3.5
(counter 1, mode 1) and display on LCD and LEDs respectively.

Interfacing Diagram:

Assembly
;Program: Count the number of times the switch ACALL LCD_DATA
is pressed at P3.4 (counter 0, mode 2) and P3.5 MOV R4, #89H
(counter 1, mode 1) and display on LCD and LEDs ACALL LCD_COMMAND
respectively ACALL DELAY
LEDS EQU P1 ;P1.3-P1.0
E EQU P2.7 MOV TMOD,#56H
RS EQU P2.6 ;counter0,mode2, counter1,mode1
LCD EQU P0 MOV TH0,#00H
ORG 00H SETB TR0
ACALL LCD_INIT MOV TH1,#00H
MOV R4, #'C' ;diplay "C1:" MOV TL1,#00H
ACALL LCD_DATA SETB TR1
MOV R4, #'1'
ACALL LCD_DATA
MOV R4, #':' AJMP AGAIN

103
AGAIN: CHECK_5: CJNE A,#5,CHECK_6
MOV R4, #83H ;display counter 0 value MOV LEDS,#0FAH
on LCD AJMP AGAIN
ACALL LCD_COMMAND CHECK_6: CJNE A,#6,CHECK_7
MOV A,TL0 MOV LEDS,#0F9H
MOV B,#10 AJMP AGAIN
DIV AB CHECK_7: CJNE A,#7,CHECK_8
MOV R3,B MOV LEDS,#0F8H
MOV B,#10 AJMP AGAIN
DIV AB CHECK_8: CJNE A,#8,CHECK_9
ADD A,#30H MOV LEDS,#0F7H
MOV R4, A AJMP AGAIN
ACALL LCD_DATA CHECK_9: CJNE A,#9,CHECK_10
MOV A,B MOV LEDS,#0F6H
ADD A,#30H AJMP AGAIN
MOV R4, A CHECK_10: CJNE A,#10,CHECK_11
ACALL LCD_DATA MOV LEDS,#0F5H
MOV A,R3 AJMP AGAIN
ADD A,#30H CHECK_11: CJNE A,#11,CHECK_12
MOV R4, A MOV LEDS,#0F4H
ACALL LCD_DATA AJMP AGAIN
CHECK_12: CJNE A,#12,CHECK_13
MOV A,TL1 ;check counter 1 value MOV LEDS,#0F3H
max 16 AJMP AGAIN
MOV B,#16 ;display on LEDs CHECK_13: CJNE A,#13,CHECK_14
DIV AB MOV LEDS,#0F2H
MOV A,B AJMP AGAIN
CJNE A,#0,CHECK_1 CHECK_14: CJNE A,#14,CHECK_15
MOV LEDS,#0FFH MOV LEDS,#0F1H
AJMP AGAIN AJMP AGAIN
CHECK_1: CJNE A,#1,CHECK_2 CHECK_15: MOV LEDS,#0F0H
MOV LEDS,#0FEH AJMP AGAIN
AJMP AGAIN
CHECK_2: CJNE A,#2,CHECK_3 LCD_INIT:
MOV LEDS,#0FDH CLR E
AJMP AGAIN CLR RS
CHECK_3: CJNE A,#3,CHECK_4 MOV R4, #38H ;Use 2 lines and 5×7
MOV LEDS,#0FCH matrix for LCD
AJMP AGAIN ACALL LCD_COMMAND
CHECK_4: CJNE A,#4,CHECK_5 ACALL DELAY
MOV LEDS,#0FBH

104
RET
MOV R4, #0CH ;LCD ON, Cursor OFF LCD_DATA: ;Function for LCD data
ACALL LCD_COMMAND SETB RS
ACALL DELAY MOV LCD, R4
MOV R4, #01H ;LCD clear SETB E
ACALL LCD_COMMAND ACALL DELAY
ACALL DELAY CLR E
RET RET
LCD_COMMAND: ;Function for LCD DELAY: ;Function for delay
command MOV R7, #200
CLR RS LOOP1: MOV R6, #200
MOV LCD, R4 LOOP: DJNZ R6, LOOP
SETB E DJNZ R7, LOOP1
ACALL DELAY RET
CLR E END

Embedded C
//Count the number of times the switch is EN=1;
pressed at P3.4 (counter 0, mode 2) and P3.5 delay();
//(counter 1, mode 1) and display on LCD and EN=0;
LEDs respectively. }
#include<reg51.h> void ldata(char ldata)
sbit RS=P2^6; { P2=ldata;
sbit EN=P2^7; RS=1;
sbit a=P1^0; EN=1;
sbit b=P1^1; delay();
sbit c=P1^2; EN=0;
sbit d=P1^3; }
sbit w=P3^4; //LED1 int arr[3], i;
sbit x=P3^5; //LED2 void main()
sbit y=P3^6; //LED3 { cmd(0x38);
sbit z=P3^7; //LED4 delay();
cmd(0x0E);
void delay() delay();
{ cmd(0x01);
int i; delay();
for(i=0;i<=10000;i++); cmd(0x80);
} delay();
void cmd(char com) delay();
{ P2=com;
RS=0;

105
TMOD=86; //01010110 w=~a;
TL0=0; //cause max delay x=~b;
TH0=0; y=~c;
TL1=0; //cause max delay z=~d;
TH1=0; cmd(0x01);
TR1=1; //start counter 1 arr[0]=TL1%10;
TR0=1; //start counter 0 arr[1]=(TL1/10)%10;
while(1) arr[2]=TL1/100;
{ P1=TL1; for(i=2;i>=0;i--)
ldata(arr[i]+0x30);
}
}

10.2.7 Count the number of times the switch is pressed at P3.4 (counter 0, mode 2) and P3.5
(counter 1, mode 2) and display on LCD which is greater

Interfacing Diagram:

Assembly
;Program: Count the number of times the switch LCD EQU P2
is pressed at P3.4 (counter 0, mode 2) and P3.5 ORG 00H
(counter 1, mode 2) and display on LCD which is ACALL LCD_INIT
greater MOV R4, #'C' ;display "C1: C2: "
E EQU P0.1 ACALL LCD_DATA
RS EQU P0.0 MOV R4, #'1'

106
ACALL LCD_DATA MOV R4, A
MOV R4, #':' ACALL LCD_DATA
ACALL LCD_DATA
MOV R4, #89H SW2_DISPLAY:
ACALL LCD_COMMAND MOV R4, #8CH ;convert C2 to ASCII
ACALL DELAY ACALL LCD_COMMAND ;display on LCD
MOV R4, #'C' MOV 31H,TL1
ACALL LCD_DATA MOV A,TL1
MOV R4, #'2' MOV B,#10
ACALL LCD_DATA DIV AB
MOV R4, #':' MOV R3,B
ACALL LCD_DATA MOV B,#10
DIV AB
MOV TMOD,#66H
;counter0,mode2, counter1, mode2 ADD A,#30H
MOV TH0,#00H MOV R4, A
MOV TH1,#00H ACALL LCD_DATA
SETB TR0 ;enable counter 0 and 1
SETB TR1 MOV A,B
HERE: ADD A,#30H
MOV R4, #83H ;convert C1 to ASCII MOV R4, A
ACALL LCD_COMMAND ;display on LCD ACALL LCD_DATA
MOV 30H,TL0
MOV A,TL0 MOV A,R3
MOV B,#10 ADD A,#30H
DIV AB MOV R4, A
MOV R3,B ACALL LCD_DATA
MOV B,#10
DIV AB MOV A,30H ;check C1 or C2 is
greater
ADD A,#30H CJNE A,31H,CHECK_GL ;and display
MOV R4, A corresponding sign
ACALL LCD_DATA MOV R4, #87H
ACALL LCD_COMMAND
MOV A,B MOV R4, #'='
ADD A,#30H ACALL LCD_DATA
MOV R4, A AJMP HERE
ACALL LCD_DATA CHECK_GL: SUBB A,31H
JC C1_LESS
MOV A,R3 MOV R4, #87H
ADD A,#30H ACALL LCD_COMMAND

107
MOV R4, #'>' LCD_COMMAND: ;Function for LCD
ACALL LCD_DATA command
AJMP HERE CLR RS
C1_LESS: MOV R4, #87H MOV LCD, R4
ACALL LCD_COMMAND SETB E
MOV R4, #'<' ACALL DELAY
ACALL LCD_DATA CLR E
AJMP HERE RET
LCD_INIT: LCD_DATA: ;Function for LCD data
CLR E SETB RS
CLR RS MOV LCD, R4
MOV R4, #38H ;Use 2 lines and 5×7 SETB E
matrix for LCD ACALL DELAY
ACALL LCD_COMMAND CLR E
ACALL DELAY RET
MOV R4, #0CH ;LCD ON, Cursor ON,
Cursor blink ON DELAY: ;Function for delay
ACALL LCD_COMMAND MOV R7, #200
ACALL DELAY LOOP1: MOV R6, #200
MOV R4, #01H ;LCD clear LOOP: DJNZ R6, LOOP
ACALL LCD_COMMAND DJNZ R7, LOOP1
ACALL DELAY RET
RET END

Embedded C
#include<reg51.h> void ldata(char ldata)
sbit RS=P0^0; { P2=ldata;
sbit EN=P0^1; RS=1;
void delay() EN=1;
{ delay();
int i; EN=0;
for(i=0;i<=10000;i++); }
} int arr[3], i, k;
void cmd(char com) void main()
{ P2=com; { cmd(0x38);
RS=0; delay();
EN=1; cmd(0x0E);
delay(); delay();
EN=0; cmd(0x01);
} while(1)

108
delay(); { k=TL0>TL1 ? TL0
cmd(0x80); : TL1;
delay(); cmd(0x01);
delay(); arr[0]=k%10;
TMOD=102; arr[1]=(k/10)%10;
TL0=0; //cause max delay arr[2]=k/100;
TH0=0; for(i=2;i>=0;i--)
TL1=0; //cause max delay ldata(arr[i]+0x30);
TH1=0; }
TR1=1; //start counter 1 }
TR0=1; //start counter 0

10.2.8 Count the number of persons entering and leaving a hall (diff doors for entry and exit)
using IR sensors connected at P3.4 (counter 0, mode 1) and P1.0(counter 2) and display
number of persons present in hall on LCD.

Interfacing Diagram:

Assembly
E EQU P2.7 EXF2 EQU 0CEH
RS EQU P2.6 ORG 00H
LCD EQU P0 ACALL LCD_INIT
RCAP2L EQU 0CAH MOV R4, 'N' ;display "No of persons"
RCAP2H EQU 0CBH ACALL LCD_DATA
TL2 EQU 0CCH MOV R4, 'o'
TH2 EQU 0CDH ACALL LCD_DATA
TR2 EQU 0CAH MOV R4, ' '
TF2 EQU 0CFH ACALL LCD_DATA
CP_RL2 EQU 0C8H MOV R4, 'o'
C_T2 EQU 0C9H ACALL LCD_DATA
EXEN2 EQU 0CBH MOV R4, 'f'

109
ACALL LCD_DATA ADD A,#30H
MOV R4, ' ' MOV R4, A
ACALL LCD_DATA ACALL LCD_DATA
MOV R4, 'p' MOV A,R3
ACALL LCD_DATA ADD A,#30H
MOV R4, 'e' MOV R4, A
ACALL LCD_DATA ACALL LCD_DATA
AJMP AGAIN
MOV R4, 'r'
LCD_INIT:
ACALL LCD_DATA
CLR E
MOV R4, 's'
CLR RS
ACALL LCD_DATA
MOV R4, #38H
MOV R4, 'o'
ACALL LCD_COMMAND
ACALL LCD_DATA
ACALL DELAY
MOV R4, 'n' MOV R4, #0CH ;LCD ON, Cursor OFF
ACALL LCD_DATA ACALL LCD_COMMAND
MOV R4, 's' ACALL DELAY
ACALL LCD_DATA MOV R4, #01H ;LCD clear
MOV TL2,#00H ACALL LCD_COMMAND
MOV TH2,#00H ACALL DELAY
SETB C_T2 ;counter 2 RET
SETB TR2 ;enable counter 2 LCD_COMMAND:
MOV TMOD,#05H ;counter 0, CLR RS
mode 1 MOV LCD, R4
MOV TL0,#00H SETB E
MOV TH0,#00H ACALL DELAY
SETB TR0 ;enable counter 0 CLR E
AGAIN: RET
MOV R4, #8CH LCD_DATA: ;Function for LCD data
SETB RS
ACALL LCD_COMMAND
MOV LCD, R4
MOV A,TL0
SETB E
CLR C
ACALL DELAY
SUBB A,TL2 ;calculate difference
CLR E
MOV B,#10 ;and display on LCD
RET
DIV AB
DELAY: ;Function for delay
MOV R3,B MOV R7, #200
MOV B,#10 LOOP1: MOV R6, #200
DIV AB LOOP: DJNZ R6, LOOP
ADD A,#30H DJNZ R7, LOOP1
MOV R4, A RET
ACALL LCD_DATA END
MOV A,B

110
Embedded C
#include<reg52.h> TR2=1; //start counter 1
sbit RS=P2^6; TR0=1; //start counter 0
sbit EN=P2^7; while(1)
void delay() { k=TL0-TL2;
{ cmd(0x01);
int i; arr[0]=k%10;
for(i=0;i<=10000;i++); arr[1]=(k/10)%10;
} arr[2]=k/100;
void cmd(char com) for(i=2;i>=0;i--)
{ P0=com; ldata(arr[i]+0x30);
RS=0; }
EN=1; }
delay();
EN=0;
}
void ldata(char ldata)
{ P0=ldata;
RS=1;
EN=1;
delay();
EN=0;
}
int arr[3], i, k;
void main()
{ cmd(0x38);
delay();
cmd(0x0E);
delay();
cmd(0x01);
delay();
cmd(0x80);
delay();
TMOD=1;
T2CON=2;
TL2=0;
TH2=0;
TL0=0;
TH0=0;

111
Chapter 11

Serial Communication
Communication is used transfer data between two devices. The devices can be controller, sensors,
actuators etc. Transmitter and receiver must follow the same rules for the communication and these rules
are known as protocols. There are two methods of data communication:

Parallel communication: Requires at least eight separate lines (in an 8-bit system) and in most cases extra
lines to synchronize the data transfer (in the case of the microcontroller, the control bus).

Serial communication: Requires only one line for the data, a second line for ground and possibly a third
line for the clock. Therefore, because serial communication requires less physical wires, it is more suitable
for transmitting data over longer distances. The obvious disadvantage of serial communication, compared
with parallel, is the reduction in the data transfer rate.

Serial data communication uses two methods

ü Synchronous method transfers a block of data at a time


ü Asynchronous method transfers a single byte at a time
11.1 UART: universal asynchronous receiver transmitter

The 8051 includes an on-chip serial port that can be programmed to operate in one of four different
modes and at a range of frequencies. In serial communication, the data is rate is known as the baud rate,
which simply means the number of bits transmitted per second. In the serial port modes that allow
variable baud rates, this baud rate is set by timer 1.

Fig 11.1

The 8051 serial port is full duplex. In other words, it can transmit and receive data at the same time. The
block diagram above shows how this is achieved. If you look at the memory map you will notice at location
99H the serial buffer special function register (SBUF). Unlike any other register in the 8051, SBUF is in fact
two distinct registers - the write-only register and the read-only register. Transmitted data is sent out from

112
the write-only register while received data is stored in the read-only register. There are two separate data
lines, one for transmission (TXD) and one for reception (RXD). Therefore, the serial port can be
transmitting data down the TXD line while it is at the same time receiving data on the RXD line.

The TXD line is pin 11 of the microcontroller (P3.1) while the RXD line is on pin 10 (P3.0). Therefore,
external access to the serial port is achieved by connecting to these pins. For example, if you wanted to
connect a Bluetooth module to the serial port you would connect the transmit pin of the keyboard to pin
10 of the 8051 and connect pin receive pin to pin 11 of the 8051.

Transmitting and Receiving Data


Essentially, the job of the serial port is to change parallel data into serial data for transmission and to
change received serial data into parallel data for use within the microcontroller.

• Serial transmission is changing parallel data to serial data.


• Serial reception is changing serial data into parallel data.
• Both are achieved through the use of shift registers.
SBUF: 8-bit register used solely for serial communication
SCON: 8-bit register used to program the start bit, stop bit, and data bits of data framing, among other
things

Bit Symbol Address Description

7 SM0 9FH serial port mode bit 0

6 SM1 9EH serial port mode bit 1

5 SM2 9DH serial port mode bit 2 - will be dealt with at a later date

4 REN 9CH receiver enable - this bit must be set to receive data

3 TB8 9BH transmit bit 8 - this is the ninth bit transmitted in the 9-bit UART modes

2 RB8 9AH receive bit 8 - this is the ninth bit received in the 9-bit UART modes

transmit interrupt flag - this bit is set by hardware when an entire byte has
1 TI 99H
been transmitted - it must be cleared by software

receive interrupt flag - this bit is set by hardware when an entire byte has
0 RI 98H
been received - it must be cleared by software

The serial control register is bit-addressable and each bit is described in the table above.

113
Bits 7 and 6 are used for putting the serial port into one of the four modes, as detailed in the table
below:

SM0 SM1 Mode Description Baud Rate

fixed - system clock frequency divided by 12


0 0 0 shift register
(machine cycle frequency)

0 1 1 8-bit UART variable - set by timer 1

fixed - system clock frequency divided by 12 or


1 0 2 9-bit UART
divided by 64

1 1 3 9-bit variable baud rate UART variable - set by timer 1

SMOD:

By default, the baud rate is equal to the timer 1 overflow frequency divided by 32. This is because a special
bit in the power control (PCON) SFR called SMOD is cleared on system reset. If this bit is set the baud rate
is doubled because the timer 1 overflow is now divided by 16 rather than 32, as shown in the below
diagram

114
11.2 UART Programming in 8051
For UART communication between two microcontrollers, transmitter of one controller is
connected to receiver of another controller and ground of both controllers should be made common
as shown in below:

11.2.1 Write a program to transmit numbers from 0 to 9 with some delay using UART to
another microcontroller in a loop

ORG 00H #include <reg51.h>


MOV TMOD,#20H ;timer 1 mode 2 void main(){
MOV TH1,#0FDH ;9600 baud TMOD=0x20; //timer 1 mode 2
MOV SCON,#50H ;enable UART TH1=0xFD; //9600 baud
SETB TR1 ;enable timer 1 SCON=0x50; //enable UART
MAIN: TR1=1; //enable timer 1
MOV A,#0 while(1){
MOV R1,#10 ;count unsigned char i;
AGAIN: MOV SBUF,A ;transnit number SBUF=i; //transnit number
HERE: JNB TI,HERE ;wait for transmission while(TI==0); //wait for tx
CLR TI ;and clear TI TI=0; //and clear TI
INC A ;next number delay();
ACALL DELAY }
DJNZ R1,AGAIN ;decrement count }
AJMP MAIN
DELAY: ;Function for delay void delay(){
MOV R7, #10 int i;
LOOP2: MOV R6, #200 for(i=0; i<1000; i++);
LOOP1: MOV R5, #200 }
LOOP: DJNZ R5, LOOP
DJNZ R6, LOOP1
DJNZ R7, LOOP2
RET
END

115
11.2.2 WAP to receive numbers from another microcontroller using UART and display it on 7-segment
display

ORG 00H #include <reg51.h>


MOV TMOD,#20H ;timer 1 mode 2 sfr SEVSEG=0x90; //P1
MOV TH1,#0FDH ;9600 baud void main(){
MOV SCON,#50H ;enable UART unsigned int chr;
SETB TR1 ;enable timer 1 TMOD=0x20; //timer 1 mode 2
MAIN: TH1=0xFD; //9600 baud
JNB RI,MAIN ;wait for reception SCON=0x50; //enable UART
CLR RI ;and clear RI TR1=1; //enable timer 1
MOV A,SBUF ;received character while(1){
CJNE A,#0,CHECK_1 while(RI==0); //wait for rx
MOV P1,#0E7H ;display on 7-segment RI=0; //and clear RI
AJMP MAIN chr=SBUF; //received char
CHECK_1: CJNE A,#1,CHECK_2 if(chr==0) //check numbers
MOV P1,#21H SEVSEG=0xE7; //display
AJMP MAIN //on 7-segment
CHECK_2: CJNE A,#2,CHECK_3 else if(chr==1)
MOV P1,#0CBH SEVSEG=0x21;
AJMP MAIN else if(chr==2)
CHECK_3: CJNE A,#3,CHECK_4 SEVSEG=0xCB;
MOV P1,#0ABH else if(chr==3)
AJMP MAIN SEVSEG=0xAB;
CHECK_4: CJNE A,#4,CHECK_5 else if(chr==4)
MOV P1,#2DH SEVSEG=0x2D;
AJMP MAIN else if(chr==5)
CHECK_5: CJNE A,#5,CHECK_6 SEVSEG=0xAE;
MOV P1,#0AEH else if(chr==6)
AJMP MAIN SEVSEG=0xEE;
CHECK_6: CJNE A,#6,CHECK_7 else if(chr==7)
MOV P1,#0EEH SEVSEG=0x23;
AJMP MAIN else if(chr==8)
CHECK_7: CJNE A,#7,CHECK_8 SEVSEG=0xEF;
MOV P1,#23H else if(chr==9)
AJMP MAIN SEVSEG=0xAF;
CHECK_8: CJNE A,#8,CHECK_9 }
MOV P1,#0EFH }
AJMP MAIN
CHECK_9: MOV P1,#0AFH
AJMP MAIN
END

116
11.3Bluetooth interfacing with 8051
Bluetooth is a wireless technology standard for exchanging data over short distances from fixed
and mobile devices, and building personal area networks (PANs). Bluetooth operates at
frequencies between 2402 and 2480 MHz, or 2400 and 2483.5 MHz including guard bands 2 MHz
wide at the bottom end and 3.5 MHz wide at the top.[15] This is in the globally unlicensed (but
not unregulated) industrial, scientific and medical (ISM) 2.4 GHz short-range radio frequency
band. HC-05 Bluetooth module is used for the below programs.

Fig 11.2

11.3.1 Write a program to transmit a string (ending with ‘.’ character) to smartphone
repeatedly using Bluetooth
Interfacing diagram:

ORG 00H #include <reg51.h>


MOV TMOD,#20H ;timer 1 mode 2 code unsigned char string[]="ETI Labs.";
MOV TH1,#0FDH ;9600 baud
MOV SCON,#50H ;enable UART void delay();
SETB TR1 ;enable timer 1 void main(){
unsigned int i=0;

117
MOV DPTR,#STRING ;initiaize DPTR to string TMOD=0x20; //timer 1 mode 2
address TH1=0xFD; //9600 baud
MAIN: SCON=0x50; //enable UART
MOV A,#0 TR1=1; //enable timer 1
MOVC A,@A+DPTR ;char to be send while(1){
CJNE A,#'.',SEND ;check end char if(string[i]=='.'){ //check end char
MOV DPTR,#STRING ;initiaize char i=0; //initiaize char
ACALL DELAY delay();
SJMP MAIN }
SEND: MOV SBUF,A ;send character else{
HERE: JNB TI,HERE SBUF=string[i]; //send char
CLR TI while(TI==0);
INC DPTR ;next character TI=0;
AJMP MAIN i=i+1; //next character
}
DELAY: ;Function for delay }
MOV R7, #10 }
LOOP2: MOV R6, #200
LOOP1: MOV R5, #200 void delay(){ //Function for delay
LOOP: DJNZ R5, LOOP unsigned int i;
DJNZ R6, LOOP1 for(i=0;i<40000;i++);
DJNZ R7, LOOP2 }
RET

STRING:
DB 'ETI Labs.'
END

11.3.2 Write a program to receive a character (y,n) from smartphone using Bluetooth and make
the LED ON/OFF connected at P1.0

Interfacing diagram:

118
LED EQU P1.0 #include <reg51.h>
ORG 00H sbit LED=P1^0;
MOV TMOD,#20H ;timer 1 mode 2 void main(){
MOV TH1,#0FDH ;9600 baud unsigned int chr;
MOV SCON,#50H ;enable UART TMOD=0x20; //timer 1 mode 2
SETB TR1 ;enable timer 1 TH1=0xFD; //9600 baud
MAIN: SCON=0x50; //enable UART
JNB RI,MAIN ;wait for reception TR1=1; //enable timer 1
CLR RI ;and clear RI while(1){
MOV A,SBUF ;received character while(RI==0); //wait for reception
CJNE A,#'y',CHECK_n ;if charcter='y' RI=0;
CLR LED ;LED ON chr=SBUF; //received character
CHECK_n: CJNE A,#'n',MAIN ;if if(chr=='y') //if charcter='y'
character='n' LED=0; //LED ON
SETB LED ;LED OFF else if(chr=='n') //if character='n'
AJMP MAIN LED=1; //LED ON
END }
}

11.3.3 Write a program to receive a character (1,2,3,4) from smartphone using Bluetooth and
turn ON the corresponding LED on P1.0, P1.1, P1.2, P1.3

Interfacing Diagram:

LED1 EQU P1.0 #include <reg51.h>


LED2 EQU P1.1 sbit LED1=P1^0;
LED3 EQU P1.2 sbit LED2=P1^1;
LED4 EQU P1.3 sbit LED3=P1^2;
ORG 00H sbit LED4=P1^3;
MOV TMOD,#20H ;timer 1 mode 2 void main(){

119
MOV TH1,#0FDH ;9600 baud unsigned int chr;
MOV SCON,#50H ;enable UART TMOD=0x20; //timer 1 mode 2
SETB TR1 ;enable timer 1 TH1=0xFD; //9600 baud
MAIN: SCON=0x50; //enable UART
JNB RI,MAIN ;wait for reception TR1=1; //enable timer 1
CLR RI ;and clear RI while(1){
MOV A,SBUF ;received character while(RI==0); //wait for Rx
CJNE A,#'1',NEXT ;check the RI=0;
received character chr=SBUF; //received char
CLR LED1 ;and turn ON if(chr=='1'){ //check
corresponding LED character
SETB LED2 LED1=0; //turn ON LED
SETB LED3 LED2=1;
SETB LED4 LED3=1;
NEXT: CJNE A,#'2',NEXT1 LED4=1;
SETB LED1 }
CLR LED2 else if(chr=='2'){
SETB LED3 LED1=1;
SETB LED4 LED2=0;
NEXT1: CJNE A,#'3',NEXT2 LED3=1;
SETB LED1 LED4=1;
SETB LED2 }
CLR LED3 else if(chr=='3'){
SETB LED4 LED1=1;
NEXT2: CJNE A,#'4',MAIN LED2=1;
SETB LED1 LED3=0;
SETB LED2 LED4=1;
SETB LED3 }
CLR LED4 else if(chr=='4'){
AJMP MAIN LED1=1;
END LED2=1;
LED3=1;
LED4=0;
}
}
}

120
11.3.4 Write a program to receive a string (enclosed within ‘<’ and ‘>’ characters) from
smartphone using Bluetooth and display it on LCD

Interfacing Diagram:

E EQU P2.7 #include <reg51.h>


RS EQU P2.6 #include <LCD_16x2_functions.c>
LCD EQU P0
ORG 00H void main(){
MOV TMOD,#20H ;timer 1 mode 2 unsigned char chr,last,i=0,*string;
MOV TH1,#0FDH ;9600 baud TMOD=0x20; //timer 1 mode 2
MOV SCON,#50H ;enable UART TH1=0xFD; //9600 baud
SETB TR1 ;enable timer 1 SCON=0x50; //enable UART
ACALL LCD_INIT TR1=1; //enable timer 1
MOV R0,#30H ;location for storing LCD_init();
MAIN: while(1){
JNB RI,MAIN ;wait for reception while(RI==0); //wait for Rx
CLR RI ;clear RI RI=0;
MOV A,SBUF ;received character chr=SBUF; //received char
CJNE A,#'<',CMP_LAST ;if start char if(chr=='<'){ //if start char
MOV R0,#30H ;move to start location i=0; //move to start
SJMP MAIN location

121
CMP_LAST: CJNE A,#'>',STORE ;if end char }
MOV R4,#01H else if(chr=='>'){ //if end char
ACALL LCD_COMMAND LCD_command(0x01);
MOV 7FH,R0 ;store last location last=i; //store last location
MOV R0,#30H for(i=0;i<last;i++) //display
REPEAT_LCD: MOV A,@R0 ;display LCD_data(*(string+i));
MOV R4,A }
ACALL LCD_DATA else{
INC R0 *(string+i)=chr; //store char
MOV A,R0 i++;
CJNE A,7FH,REPEAT_LCD }
AJMP MAIN }
STORE: MOV @R0,A ;store characters }
INC R0
AJMP MAIN
END

11.3.5 Write a program to send DHT11 humidity data to smartphone using Bluetooth.

Interfacing Diagram:

DHT11 EQU P2.0 #include<reg51.h>


ORG 00H sbit DHT11=P2^0;
SETB DHT11 void initial_delay();
MOV TMOD,#21H ;timer 1 mode 2
MOV TH1,#0FDH ;9600 baud void main(){
MOV SCON,#50H ;enable UART unsigned int bytes,bits;
SETB TR1 ;enable timer 1 unsigned char rec_byte,data_array[5];
MAIN: unsigned char disp_hum[3],bit_time;
MOV R2,#5 ;count for bytes DHT11=1;
CLR DHT11 ;10uS pulse TMOD=0x21; //timer 1 mode 2
ACALL DELAY1 TH1=0xFD; //9600 baud
SETB DHT11 SCON=0x50; //enable UART

122
HERE: JB DHT11,HERE ;wait for start bit TR1=1; //enable timer 1
HERE1: JNB DHT11,HERE1 while(1){
HERE2: JB DHT11,HERE2 DHT11=0; //10uS pulse
NEXT_BYTE: MOV R1,#8 ;count for bits initial_delay();
LOOP: JNB DHT11,LOOP ;wait for new bit DHT11=1;
RL A while(DHT11); //wait for start bit
MOV R0,A while(!DHT11);
SETB TR0 ;timer 0 for calculating while(DHT11);
bit time for(bytes=0;bytes<5;bytes++){
HERE41: JB DHT11,HERE41 ;wait for for(bits=0;bits<8;bits++){
bit time while(!DHT11);
CLR TR0 TR1=1; //timer 0 for bit time
MOV A,TL0 ;bit time while(DHT11);
SUBB A,#50D ;check bit time for 0/1 TR1=0;
MOV A,R0 bit_time=TL1;
JB PSW.7, NEXT ;if bit=1, TL1=0;
SETB ACC.0 ;set bit rec_byte=rec_byte<<1;
SJMP ESC if(bit_time>50) //if bit=1,
NEXT: CLR ACC.0 ;if bit=0, clear bit rec_byte=rec_byte|1; //set
ESC: MOV TL0,#00D bit
CLR PSW.7 }
DJNZ R1,LOOP ;next bit data_array[bytes]=rec_byte;
MOV R5,A }
MOV A,#30H ;store bytes 30H to 35H SBUF='R';
ADD A,R2 while(TI==0);
MOV R0,A TI=0;
MOV A,R5 SBUF='H';
MOV @R0,A while(TI==0);
DJNZ R2,NEXT_BYTE ;next byte TI=0;
SBUF=':';
MOV SBUF,#'R' ;send humidity data while(TI==0);
HERE21: JNB TI,HERE21 TI=0;
CLR TI disp_hum[0]=data_array[0]%10
MOV SBUF,#'H' disp_hum[1]=(data_array[0]/10)%10;
HERE22: JNB TI,HERE22 disp_hum[2]=data_array[0]/100;
CLR TI for(bytes=3;bytes>0;bytes--)
MOV SBUF,#':' SBUF=disp_hum[bytes-1]+0x30;
HERE23: JNB TI,HERE23 SBUF=':';
CLR TI while(TI==0);
MOV A,35H TI=0;
MOV B,#10 }

123
DIV AB }
MOV R3,B
MOV B,#10 void initial_delay(){
DIV AB TH0=0xB9;
ADD A,#30H TL0=0xB0;
MOV SBUF,A TR0=1;
HERE3: JNB TI,HERE3 while(!TF0);
CLR TI TR0=0;
MOV A,B TF0=0;
ADD A,#30H }
MOV SBUF,A
HERE4: JNB TI,HERE4
CLR TI
MOV A,R3
ADD A,#30H
MOV SBUF,A
HERE5: JNB TI,HERE5
CLR TI
MOV SBUF,#'%'
HERE6: JNB TI,HERE6
CLR TI
AJMP MAIN

DELAY1: ;10uS delay for DHT11


MOV TH0,#0B9H
MOV TL0,#0B0H
SETB TR0
HERE51: JNB TF0,HERE51
CLR TR0
CLR TF0
RET
END

124
11.4 GSM Interfacing with 8051

GSM (Global System for Mobile communications) is a standard developed by the European
Telecommunications Standards Institute (ETSI) to describe the protocols for second-
generation digital cellular networks used by mobile devices. A GSM device can be used to
make & receive calls and to send and receive SMS. A GSM network consists of the following
components:
• A Mobile Station: It is the mobile phone which consists of the transceiver, the display and
the processor and is controlled by a SIM card operating over the network.
• Base Station Subsystem: It acts as an interface between the mobile station and the network
subsystem. It consists of the Base Transceiver Station which contains the radio transceivers
and handles the protocols for communication with mobiles. It also consists of the Base
Station Controller which controls the Base Transceiver station and acts as a interface
between the mobile station and mobile switching center.
• Network Subsystem: It provides the basic network connection to the mobile stations. The
basic part of the Network Subsystem is the Mobile Service Switching Centre which provides
access to different networks like ISDN, PSTN etc. It also consists of the Home Location
Register and the Visitor Location Register which provides the call routing and roaming
capabilities of GSM. It also contains the Equipment Identity Register which maintains an
account of all the mobile equipments wherein each mobile is identified by its own IMEI
number. IMEI stands for International Mobile Equipment Identity.

Figure 11.3: GSM Architecture

GSM modules can be interfaced with 8051 using UART pins as shown in the below
figure.

125
11.4.1 Write a program to send an SMS to mobile number

ORG 00H NEXT2: CLR A


MOV TMOD,#20H ;timer 1 mode 2 MOVC A,@A+DPTR
MOV TH1,#0FDH ;9600 baud CJNE A,#0x1A,SEND_TEXT
MOV SCON,#50H ;enable UART MOV A,#0x1A
SETB TR1 ;enable timer 1 ACALL SEND
MAIN: SJMP HERE
MOV DPTR,#TEXT_MODE ;text mode SEND_TEXT:
NEXT: CLR A ACALL SEND
MOVC A,@A+DPTR INC DPTR
CJNE A,#0x0D,SEND_MODE SJMP NEXT2
MOV A,#0x0D HERE: AJMP HERE
ACALL SEND DELAY: ;Function for delay
SJMP MOB_NUM MOV R7, #10
SEND_MODE: ACALL SEND LOOP2: MOV R6, #200
INC DPTR LOOP1: MOV R5, #200
SJMP NEXT LOOP: DJNZ R5, LOOP
DJNZ R6, LOOP1
MOB_NUM: ;mobile number DJNZ R7, LOOP2
MOV DPTR,#MOBILE_NUMBER RET
NEXT1: CLR A SEND: ;UART send
MOVC A,@A+DPTR CLR TI
CJNE A,#0x0D,SEND_NUM MOV SBUF,A
MOV A,#0x0D WAIT: JNB TI,WAIT
ACALL SEND RET
SJMP SMS_TXT TEXT_MODE: DB "AT+CMGF=1",0x0D
SEND_NUM: ACALL SEND MOBILE_NUMBER: DB
INC DPTR "AT+CMGS=",34,"+91xxxxxxxxxx",34,0x0D
SJMP NEXT1 SMS_TEXT: DB "ETI Labs",0x1A
SMS_TXT: END
MOV DPTR,#MOBILE_NUMBER ;SMS text

126
#include <reg51.h>

code unsigned char *TEXT_MODE[]={"AT+CMGF=1", 0x0D};


code unsigned char *MOBILE_NUMBER[]={"AT+CMGS=",34,"+918860340719",34,0x0D};
code unsigned char *SMS_TEXT[]={"Hello",0x1A};

void Tx_data(unsigned char dat);

void main(){
unsigned int i=0;
TMOD=0x20; //timer 1 mode 2
TH1=0xFD; //9600 baud
SCON=0x50; //enable UART
TR1=1; //enable timer 1
while(*TEXT_MODE[i]!=0x0D){ //text mode (AT+CMGF=1)
Tx_data(*TEXT_MODE[i]);
i++;
}
Tx_data(0x0D);
i=0;
while(*MOBILE_NUMBER[i]!=0x0D){ //mobile number (AT+CMGS="number")
Tx_data(*MOBILE_NUMBER[i]);
i++;
}
Tx_data(0x0D);
i=0;
while(*SMS_TEXT[i]!=0x1A){ //SMS text
Tx_data(*SMS_TEXT[i]);
i++;
}
Tx_data(0x1A);
}

void Tx_data(unsigned char dat){ //UART send


TI=0;
SBUF=dat;
while(TI==0);
}

127
11.4.2 Write a program to read the latest SMS (10 characters) and display it on LCD

Interfacing Diagram:

E EQU P2.7 INC DPTR


RS EQU P2.6 SJMP NEXT
LCD EQU P0 FRST_SMS: MOV DPTR,#FIRST_SMS ;first SMS
ORG 00H (AT+CMGR=1)
MOV TMOD,#20H ;timer 1 mode 2 NEXT1: CLR A
MOV TH1,#0FDH ;9600 baud MOVC A,@A+DPTR
MOV SCON,#50H ;enable UART CJNE A,#0x0D,SMS_1
SETB TR1 ;enable timer 1 MOV A,#0x0D
ACALL LCD_INIT ACALL SEND
MAIN: SJMP HERE
MOV DPTR,#TEXT_MODE ;text SMS_1: ACALL SEND
mode (AT+CMGF=1) INC DPTR
NEXT: CLR A SJMP NEXT1
MOVC A,@A+DPTR HERE: ACALL REC
CJNE A,#0x0D,SEND_MODE CJNE A,#'+',HERE
MOV A,#0x0D HERE1: ACALL REC
ACALL SEND CJNE A,#0DH,HERE1
SJMP FRST_SMS ACALL REC
SEND_MODE: ACALL SEND CJNE A,#0DH,HERE1

128
MOV R0,#30H ACALL LCD_COMMAND
MOV R1,#3 ACALL DELAY
REC_MSG: ;receive the SMS text RET
ACALL REC
MOV @R0,A LCD_COMMAND: ;Function for LCD
INC R0 command
DJNZ R1,REC_MSG CLR RS
MOV R0,#30H MOV LCD, R4
MOV R1,#3 SETB E
MOV R4, #01H ;display SMS on LCD ACALL DELAY
ACALL LCD_COMMAND CLR E
LCD_MSG: RET
MOV A,@R0
MOV R4,A LCD_DATA: ;Function for LCD data
ACALL LCD_DATA SETB RS
DJNZ R1,LCD_MSG MOV LCD, R4
AJMP MAIN SETB E
ACALL DELAY
SEND: ;UART send CLR E
CLR TI RET
MOV SBUF,A
WAIT: JNB TI,WAIT DELAY: ;Function for delay
RET MOV R7, #200
LOOP1: MOV R6, #200
REC: ;UART receive LOOP: DJNZ R6, LOOP
JNB RI,REC DJNZ R7, LOOP1
CLR RI RET
MOV A,SBUF
RET TEXT_MODE: DB "AT+CMGF=1",0x0D
FIRST_SMS: DB "AT+CMGR=1",0x0D
LCD_INIT: END
CLR E
CLR RS
MOV R4, #38H ;Use 2 lines and 5×7
matrix for LCD
ACALL LCD_COMMAND
ACALL DELAY
MOV R4, #0CH ;LCD ON, Cursor OFF
ACALL LCD_COMMAND
ACALL DELAY
MOV R4, #01H ;LCD clear

129
#include <reg51.h> Tx_data(0x0D);
#include <LCD_16x2_functions.c> while(Rx_data()!='+'); //rec SMS
code unsigned char while(Rx_data()!=0x0D);
*TEXT_MODE[]={"AT+CMGF=1", 0x0D}; while(Rx_data()!=0x0D);
code unsigned char for(i=0;i<5;i++) //receive SMS text
*FIRST_SMS[]={"AT+CMGR=1",0x0D}; SMS_TEXT[i]=Rx_data();
LCD_command(0x01); //display SMS
void Tx_data(unsigned char dat); for(i=0;i<5;i++)
unsigned char Rx_data(); LCD_data(SMS_TEXT[i]);
void main(){ }
unsigned char i=0,SMS_TEXT[5];
TMOD=0x20; //timer 1 mode 2 void Tx_data(unsigned char dat){ //UART
TH1=0xFD; //9600 baud send
SCON=0x50; //enable UART TI=0;
TR1=1; //enable timer 1 SBUF=dat;
LCD_init(); while(TI==0);
while(*TEXT_MODE[i]!=0x0D){ //text }
mode (AT+CMGF=1)
Tx_data(*TEXT_MODE[i]); unsigned char Rx_data(){ //UART receive
i++; while(RI==0);
} RI=0;
Tx_data(0x0D); return SBUF;
i=0; }
while(*FIRST_SMS[i]!=0x0D){ //first
SMS (AT+CMGR=1)
Tx_data(*FIRST_SMS[i]);
i++;
}

11.4.3 Write a program to make a call to a mobile number


ORG 00H #include <reg51.h>
MOV TMOD,#20H ;timer 1 mode 2 code unsigned char *CALL_NUMBER[]=
MOV TH1,#0FDH ;9600 baud {"ATD+91xxxxxxxxxx;", 0x0D};
MOV SCON,#50H ;enable UART sbit led=P1^0;
SETB TR1 ;enable timer 1 void Tx_data(unsigned char dat);
MAIN: void main(){
MOV DPTR,#CALL_NUMBER ;make unsigned int i=0;
call (ATD number;) TMOD=0x20; //timer 1 mode 2
NEXT: CLR A TH1=0xFD; //9600 baud
MOVC A,@A+DPTR SCON=0x50; //enable UART

130
CJNE A,#0x0D,SEND_CALL TR1=1; //enable timer 1
MOV A,#0x0D led=0;
ACALL SEND while(*CALL_NUMBER[i]!=0x0D){
SJMP HERE //make call (ATD number;)
SEND_CALL: ACALL SEND Tx_data(*CALL_NUMBER[i]);
INC DPTR i++;
SJMP NEXT }
HERE: SJMP HERE Tx_data(0x0D);
led=0;
SEND: ;UART send while(1);
CLR TI }
MOV SBUF,A void Tx_data(unsigned char dat){ //UART send
WAIT: JNB TI,WAIT TI=0;
RET SBUF=dat;
while(TI==0);
CALL_NUMBER: DB "ATD+91xxxxxxxxxx;",0x0D }
END

11.4.4 Write a program to receive a call from a mobile number


ORG 00H #include <reg51.h>
MOV TMOD,#20H ;timer 1 mode 2
MOV TH1,#0FDH ;9600 baud void Tx_data(unsigned char dat);
MOV SCON,#50H ;enable UART unsigned char Rx_data();
SETB TR1 ;enable timer 1 void main(){
MAIN: unsigned int i=0;
ACALL REC ;check for RING TMOD=0x20; //timer 1 mode 2
CJNE A,#'R',MAIN TH1=0xFD; //9600 baud
ACALL REC SCON=0x50; //enable UART
CJNE A,#'I',MAIN TR1=1; //enable timer 1
ACALL REC if(Rx_data=='R'){//check for RING
CJNE A,#'N',MAIN if(Rx_data=='I'){
ACALL REC if(Rx_data=='N'){
CJNE A,#'G',MAIN if(Rx_data=='G'){
Tx_data('A'); //attend the call
MOV A,#"A" ;attend the call Tx_data('T');
ACALL SEND Tx_data('A');
MOV A,#"T" }
ACALL SEND }
MOV A,#"A" }
ACALL SEND }
MOV A,#0DH }

131
ACALL SEND
AJMP MAIN void Tx_data(unsigned char dat){ //UART
send
SEND: ;UART send TI=0;
CLR TI SBUF=dat;
MOV SBUF,A while(TI==0);
WAIT: JNB TI,WAIT }
RET
unsigned char Rx_data(){ //UART receive
REC: ;UART receive while(RI==0);
JNB RI,REC RI=0;
CLR RI return SBUF;
MOV A,SBUF }
RET
END

11.5 GPS Interfacing with 8051

The Global Positioning System (GPS) is a satellite-based radio navigation system owned
by the United States government and operated by the United States Air Force. It is a global
navigation satellite system that provides geolocation and time information to a GPS
receiver anywhere on or near the Earth using four or more GPS satellites as shown in the
below figure.

Figure 11.4: GPS Navigation System

132
11.5.4 Write a program to receive data from GPS device and display latitude and longitude on LCD

Interfacing Diagram:

E EQU P2.7 CJNE A,#'R',MAIN


RS EQU P2.6 ACALL REC
LCD EQU P0 CJNE A,#'M',MAIN
ORG 00H ACALL REC
MOV TMOD,#20H ;timer 1 mode 2 CJNE A,#'C',MAIN
MOV TH1,#0FDH ;9600 baud
MOV SCON,#50H ;enable UART HERE: ACALL REC ;ignore other fields
SETB TR1 ;enable timer 1 CJNE A,#',',HERE
ACALL LCD_INIT HERE1: ACALL REC
MAIN: CJNE A,#',',HERE1
ACALL REC ;start string $GPRMC ACALL REC
CJNE A,#'$',MAIN CJNE A,#'A',MAIN
ACALL REC HERE2: ACALL REC
CJNE A,#'G',MAIN CJNE A,#',',HERE2
ACALL REC MOV R0,#30H
CJNE A,#'P',MAIN MOV R1,#11
ACALL REC ACALL LCD_COMMAND
LAT: ;receive laitude data ACALL DELAY

133
ACALL REC MOV R4, #0CH ;LCD ON, Cursor OFF
MOV @R0,A ACALL LCD_COMMAND
DJNZ R1,LAT ACALL DELAY
HERE3: ACALL REC MOV R4, #01H ;LCD clear
CJNE A,#',',HERE3 ACALL LCD_COMMAND
MOV R1,#12 ACALL DELAY
LONG: ;receive longitude data RET
ACALL REC
MOV @R0,A LCD_COMMAND: ;Function for LCD
DJNZ R1,LONG command
MOV R4, #80H CLR RS
ACALL LCD_COMMAND MOV LCD, R4
SETB E
LCD_DISP: ;display latitude on LCD row 1 ACALL DELAY
MOV R0,30H CLR E
MOV R1,#11 RET
LAT_DISP:
MOV A,@R0 LCD_DATA: ;Function for LCD data
INC R0 SETB RS
MOV R4,A MOV LCD, R4
ACALL LCD_DATA SETB E
DJNZ R1,LAT_DISP ACALL DELAY
CLR E
MOV R4, #0C0H ;display longitude on LCD RET
row 2
ACALL LCD_COMMAND DELAY: ;Function for delay
MOV R1,#12 MOV R7, #200
LONG_DISP: LOOP1: MOV R6, #200
MOV A,@R0 LOOP: DJNZ R6, LOOP
INC R0 DJNZ R7, LOOP1
MOV R4,A RET
ACALL LCD_DATA
DJNZ R1,LONG_DISP SEND: ;UART send
AJMP MAIN CLR TI
MOV SBUF,A
LCD_INIT: WAIT: JNB TI,WAIT
CLR E RET
CLR RS
MOV R4, #38H ;Use 2 lines and 5×7 REC: ;UART receive
matrix for LCD
WAIT1: JNB RI,WAIT1

134
CLR RI
MOV A,SBUF
RET
END

#include<reg51.h> for (i=0; i<12; i++)


#include<LCD_16x2_functions.c>
unsigned char Rx_data(); LON[i] = Rx_data();
void main (){
unsigned int LAT[11], LON[12]; //display latitude on LCD row 1
unsigned char Temp, i; LCD_command (0x80);
TMOD=0x20; //timer 1 mode 2 for (i=0; i<11; i++)
TH1=0xFD; //9600 baud
SCON=0x50; //8N1, enable UART Rx LCD_data(LAT[i]);
TR1=1; //enable timer 1
LCD_init(); //display longitude on LCD row 2
while(1){
if (Rx_data() == '$'){ //start string LCD_command (0xc0);
$GPRMC
if( Rx_data() == 'G'){ for (i=0; i<12; i++)
if (Rx_data() == 'P'){ LCD_data(LON[i]);
if (Rx_data() == 'R'){
if (Rx_data() == 'M'){ }

if (Rx_data() == 'C'){ }

while (Rx_data() != ','); //ignore other }


}
while (Rx_data() != ','); }
}
Temp = Rx_data(); //check for A }
if (Temp == 'A'){ }
}
while (Rx_data() != ',')
//receive laitude data unsigned char Rx_data(){ //UART Rx
for (i=0; i<11; i++) unsigned char str;
while(RI==0);
LAT[i] = Rx_data(); str=SBUF;
RI=0;
while (Rx_data() != ','); return str;
}
//while (Rx_data() != ',');

//receive longitude data

135
Chapter 12

Interrupt
The interrupts refer to a notification, communicated to the controller, by a hardware device or
software, on receipt of which controller momentarily stops and responds to the interrupt. 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 is a piece of code that
tells the processor or controller what to do when the interrupt occurs. After the execution of ISR,
controller returns back to the instruction it has jumped from (before the interrupt was
received). The interrupts can be either hardware interrupts or software interrupts.

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.

Interrupt: The controller responds to only when an interruption occurs. Thus in interrupt method,
controller is not required to regularly monitor the status (flags, signals etc.) of interfaced and inbuilt
devices.

Hardware and Software interrupt


The interrupts in a controller can be either hardware or software. If the interrupts are generated by
the controller’s inbuilt devices, like timer interrupts; or by the interfaced devices, they are called
the hardware interrupts. If the interrupts are generated by a piece of code, they are termed as
software interrupts.

12.1 8051 Interrupts


The 8051 controller has six hardware interrupts of which five are available to the programmer.
These are as follows:

136
1. RESET interrupt - This is also known as Power on Reset (POR). When the RESET interrupt
is received, the controller restarts executing code from 0000H location. This is an interrupt which
is not available to or, better to say, need not be available to the programmer.

2. Timer interrupts - Each Timer is associated with a Timer interrupt. A timer interrupt notifies
the microcontroller that the corresponding Timer has finished counting.

3. External interrupts - There are two external interrupts EX0 and EX1 to serve external devices.
Both these interrupts are active low. In 8051, P3.2 (INT0) and P3.3 (INT1) pins are available for
external interrupts 0 and 1 respectively. An external interrupt notifies the microcontroller that an
external device needs its service.

4. Serial interrupt - This interrupt is used for serial communication. When enabled, it notifies the
controller whether a byte has been received or transmitted.

12.1.1 Timer interrupt


12.1.1.1 Blink LED using timer 0 (mode 1) interrupt

Interfacing Diagram:

LED EQU P1.0 #include<reg51.h>


ORG 00H ;reset location sbit LED=P1^0;
AJMP MAIN void ISR_T0() interrupt 1{ //ISR timer 0
LED=~LED; //complement LED
ORG 0BH ;timer 0 interrupt location TF0=0; //reset timer flag
AJMP ISR_T0 }

ORG 30H void main(){


MAIN: IE=0x82; //enable timer 0 interrupt
MOV IE,#82H ;enable timer 0 interrupt TMOD=0x01; //timer 0, mode 1
MOV TMOD,#01H ;timer 0, mode 1 TH0=0; //initialize timer 0

137
MOV TH0,#0 ;initialize timer 0 TL0=0;
MOV TL0,#0 TR0=1; //start timer 0
SETB TR0 ;start timer 0 while(1);
HERE: SJMP HERE }

ISR_T0: ;ISR timer 0


CPL LED ;complement LED
CLR TF0 ;reset timer flag
RETI
END

12.1.1.2 Control the LED using switch while simultaneously blink another LED using timer 1
(mode 1) interrupt

Interfacing Diagram:

LED_INT EQU P1.0 #include<reg51.h>


LED EQU P1.1 sbit LED_INT=P1^0;
SWITCH EQU P3.2 sbit LED=P1^1;
ORG 00H ;reset location sbit SWITCH=P3^2;
AJMP MAIN
void ISR_T1() interrupt 3{ //ISR timer 1
ORG 1BH ;timer 1 interrupt location LED=~LED_INT; //complement LED
AJMP ISR_T0 TF0=0; //reset timer flag
}
ORG 30H
MAIN: void main(){
MOV IE,#88H ;enable timer 0 interrupt IE=0x88; //enable timer 1
MOV TMOD,#10H ;timer 1, mode 1 interrupt
MOV TH1,#0 ;initialize timer 1 TMOD=0x10; //timer 1, mode 1
MOV TL1,#0 TH1=0; //initialize timer 1
SETB TR1 ;start timer 1 TL1=0;

138
HERE: JNB SWITCH,LED_ON ;if switch not pressed TR1=1; //start timer 1
SETB LED ;LED OFF while(1){
SJMP HERE if(SWITCH)
LED_ON: CLR LED ;if switch pressed, LED ON LED=1;
SJMP HERE else
LED=0;
ISR_T0: ;ISR timer 1 }
CPL LED_INT ;complement LED }
CLR TF0 ;reset timer flag
RETI
END

12.1.2 External hardware interrupt


12.1.2.1 Blink an LED continuously. Use external interrupt 1 to stop blinking and turn off the
LED

Interfacing Diagram:

LED EQU P1.0 #include<reg51.h>


ORG 00H ;reset location sbit LED=P1^0;
AJMP MAIN void delay();
void ISR_EXT1() interrupt 3{ //ISR external 1
ORG 13H ;external interrupt 1 location LED=1; //Turn OFF LED
AJMP ISR_EXT1 }

ORG 30H void main(){


MAIN: IE=0x84; //enable external interrupt 1
MOV IE,#84H while(1){ //blink LED
BLINK: ;blink LED LED=1;
SETB LED delay();
ACALL DELAY LED=0;
CLR LED delay();
ACALL DELAY }
AJMP BLINK }

139
DELAY: ;Function for delay void delay(){ //Function for delay
MOV R7, #10 unsigned int i;
LOOP2: MOV R6, #200 for(i=0;i<40000;i++);
LOOP1: MOV R5, #200 }
LOOP: DJNZ R5, LOOP
DJNZ R6, LOOP1
DJNZ R7, LOOP2
RET

ISR_EXT1: ;ISR external 1


SETB LED ;Turn OFF LED
RETI
END

12.1.2.2 Control an LED according to input from IR sensor. When external interrupt 0 is triggered,
make the led OFF for 10 seconds using timer 1 mode 1.

Interfacing Diagram:

LED EQU P1.0 #include<reg51.h>


IR EQU P2.0 sbit LED=P1^0;
ORG 00H ;reset location sbit IR=P2^0;
AJMP MAIN
void delay_timer();
ORG 03H ;external interrupt 0 location void ISR_EXT0() interrupt 3{ //ISR external 0
AJMP ISR_EXT0 unsigned char i;
LED=1; //Turn OFF LED
ORG 30H for(i=0;i<40;i++)//10 S Delay
MAIN: delay_timer();
MOV IE,#81H ;enabble external interrput 0 }
MOV TMOD,#10H
CHECK: JNB IR,LED_ON ;if IR=1, void main(){

140
SETB LED ;LED OFF IE=0x81; //enable external
SJMP CHECK interrupt 0
LED_ON: CLR LED ;if IR=0, LED ON TMOD=0x10; //timer 1, mode 1
SJMP CHECK while(1){
if(IR) //if IR=1,
ISR_EXT0: ;ISR external 1 LED=1; //LED OFF
SETB LED ;LED OFF for 10 sec else
MOV R0,#140 LED=0; //else LED ON
TIMES_140: ;10 S Delay }
ACALL DELAY_TIMER }
DJNZ R0,TIMES_140
RETI void delay_timer(){ //delay using timer 1
TL1=0x18;
DELAY_TIMER: ;delay using timer 1 TH1=0x02;
MOV TL1,#18H TR1=1;
MOV TH1,#02H while(TF1==0);
SETB TR1 TR1=0;
AGAIN: JNB TF0,AGAIN TF1=0;
CLR TR0 }
CLR TF0
RET
END

12.1.3 Serial interrupt


12.1.3.1 Blink an LED continuously with some delay. Make the LED ON for 5 seconds when a
character is received on serial port using timer 0 mode 1.

Interfacing Diagram:

141
LED EQU P1.0 #include<reg51.h>
ORG 00H ;reset location sbit LED=P1^0;
AJMP MAIN
void delay();
ORG 23H ;serial interrupt location void delay_timer();
AJMP ISR_Serial void ISR_Serial() interrupt 4{ //ISR Serial
unsigned char i;
ORG 30H IE=0x00; //disable interrupts
MAIN: RI=0;
MOV IE,#90H ;enable serial interrupt LED=0; //Turn ON LED for 5 sec
MOV TMOD,#21H ;timer 1 mode 2, for(i=0;i<70;i++)
timer 0 mode 1 delay_timer();
MOV TH1,#0FDH ;9600 baud IE=0x90; //enable interrupts
MOV SCON,#50H }
SETB TR1
HERE: CPL LED ;blink LED void main(){
ACALL DELAY IE=0x90; //enable serial
SJMP HERE interrupt
TMOD=0x21; //timer 1 mode 2,
ISR_Serial: ;ISR serial timer 0 mode 1
MOV IE,#00H ;disable interrupts TH1=0xFD;
CLR RI SCON=0x50;
CLR LED ;Turn ON LED for 5 sec TR1=1;
MOV R0,#70 while(1){
TIMES_70: ;5 S Delay LED=~LED; //blink LED
ACALL DELAY_TIMER delay();
DJNZ R0,TIMES_70 }
MOV IE,#90H ;enable interrupts }
RETI
void delay_timer(){ //delay using timer 0
DELAY_TIMER: ;delay using timer 0 TL0=0x18;
MOV TL0,#18H TH0=0x02;
MOV TH0,#02H TR0=1;
SETB TR0 while(TF0==0);
AGAIN: JNB TF0,AGAIN TR0=0;
CLR TR0 TF0=0;
CLR TF0 }
RET
void delay(){ //Function for delay
DELAY: ;Function for delay unsigned int i;
MOV R7, #10 for(i=0;i<40000;i++);

142
LOOP2: MOV R6, #200 }
LOOP1: MOV R5, #200
LOOP: DJNZ R5, LOOP
DJNZ R6, LOOP1
DJNZ R7, LOOP2
RET
END

11.1.4.2 Blink an LED continuously with some delay. Make one of the 3 LEDs ON according to the
character received (‘1’, ‘2’, ‘3’) on serial port.

Interfacing Diagram:

LED EQU P1.0 #include<reg51.h>


LED1 EQU P1.1 sbit LED=P1^0;
LED2 EQU P1.2 sbit LED1=P1^1;
LED3 EQU P1.3 sbit LED2=P1^2;
ORG 00H ;reset location sbit LED3=P1^3;
AJMP MAIN
void delay();
ORG 23H ;serial interrupt location void ISR_Serial() interrupt 4{ //ISR Serial
AJMP ISR_Serial unsigned char chr;
IE=0x00; //disable interrupts
ORG 30H RI=0;
MAIN: chr=SBUF; //read received character
MOV IE,#90H ;enable serial interrupt if(chr=='1'){ //check recived character
MOV TMOD,#20H ;timer 1 mode 2 and
MOV TH1,#0FDH ;9600 baud LED1=0; //turn ON
MOV SCON,#50H corresponding LED
SETB TR1 LED2=1;
HERE: LED3=1;
CPL LED ;LED blink }

143
ACALL DELAY else if(chr=='2'){
SJMP HERE LED1=1;
LED2=0;
ISR_Serial: ;ISR serial LED3=1;
MOV IE,#00H ;disable interrupts }
CLR RI else if(chr=='3'){
MOV A,SBUF ;read received character LED1=1;
CJNE A,#'1',TWO ;check recived LED2=1;
character and LED3=0;
CLR LED1 ;turn ON LED }
SETB LED2 IE=0x90; //enable interrupts
SETB LED3 }
TWO: CJNE A,#'2',THREE
CLR LED2 void main(){
SETB LED1 IE=0x90; //enable serial interrupt
SETB LED3 TMOD=0x20; //timer 1 mode 2
THREE: CJNE A,#'2',LAST TH1=0xFD; //timer 1 settings for
CLR LED3 serial
SETB LED1 SCON=0x50;
SETB LED2 TR1=1;
LAST: MOV IE,#90H ;enable interrupts while(1){
RETI LED=~LED; //blink LED
delay();
DELAY: ;Function for delay }
MOV R7, #10 }
LOOP2: MOV R6, #200
LOOP1: MOV R5, #200 void delay(){ //Function for delay
LOOP: DJNZ R5, LOOP unsigned int i;
DJNZ R6, LOOP1 for(i=0;i<40000;i++);
DJNZ R7, LOOP2 }
RET
END

144
12.2 Interrupt priority
12.2.1 Blink LED1 using timer 1 (mode 1) interrupt and turn ON LED2 when there is external interrupt 0
and observe the priority.

Interfacing Diagram:

LED1 EQU P1.0 #include<reg51.h>


LED2 EQU P1.1 sbit LED1=P1^0;
ORG 00H ;reset location sbit LED2=P1^1;
AJMP MAIN
void delay();
ORG 03H ;external interrupt 0 location void ISR_T1() interrupt 3{ //ISR timer 1
AJMP ISR_EXT0 LED1=~LED1; //blink LED1
TF1=0;
ORG 0BH ;timer 1 interrupt location }
AJMP ISR_T1
void ISR_EXT0() interrupt 0{ //ISR external 0
ORG 30H LED2=0; //turn ON LED 2
MAIN: delay();
MOV IE,#89H ;enable EXT 0 and TIM 1 }
interrupts
MOV TMOD,#10H ;timer 1, mode 1 void main(){
MOV TH1,#0 IE=0x89; //enable EXT 0 and TIM 1
MOV TL1,#0 interrupts
SETB TR1 TMOD=0x10; //timer 1, mode 1
HERE: SJMP HERE TH1=0;
TL1=0;
ISR_T1: ;ISR timer 1 TR1=1;
CPL LED1 ;blink LED1 while(1);
CLR TF1 }
RETI
ISR_EXT0: ;ISR external interrupt 0 void delay(){ //Function for delay
CLR LED2 ;turn ON LED 2 unsigned int i;
RETI for(i=0;i<40000;i++);
END }

145
12.2.2 Turn ON/OFF LED when receiving y/n characters using serial interrupt and turn OFF LED when
there is external interrupt 0 and observe the priority.

Interfacing Diagram:

LED EQU P1.0 #include<reg51.h>


ORG 00H ;reset location sbit LED=P1^0;
AJMP MAIN
void ISR_EXT0() interrupt 0{ //ISR external 0
ORG 03H ;external interrupt 0 location
LED=1;
AJMP ISR_EXT0
}
ORG 23H ;serial interrupt location
AJMP ISR_Serial void ISR_Serial() interrupt 4{ //ISR Serial
unsigned char chr;
ORG 30H IE=0x81; //disable serial interrupt
MAIN: RI=0;
MOV IE,#91H ;enable EXT 0 and serial chr=SBUF; //read received character
interrupts if(chr=='y'){ //if character='y'
HERE: SJMP HERE
LED=0; //LED ON
}
ISR_Serial: ;ISR serial interrupt
else if(chr=='n'){
MOV IE,#81H ;disable serial interrupt
CLR RI LED=1; //LED OFF
MOV A,SBUF }
CJNE A,#'y',NEXT ;if character='y' IE=0x91; //enable interrupts
CLR LED ;LED ON }
SJMP NEXT1
NEXT: CJNE A,#'n',NEXT1 ;if character='y' void main(){
SETB LED ;LED OFF IE=0x91; //enable EXT 0 and serial
NEXT1:
interrupts
MOV IE,#91H ;enable interrupts
while(1);
RETI
}
ISR_EXT0:
SETB LED
RETI
END

146
CHAPTER 13

ADC and DAC Interfacing with 8051


In modern life, electronic devices are frequently used in different fields such as communication,
transportation, entertainment, etc. Analog to Digital Converter (ADC) and Digital to Analog
Converter (DAC) are very useful components in Embedded systems. Since most real-world signals
are analog, these two converting interfaces are necessary to process the analog signals by digital
devices such as microcontrollers.

13.1ADC Interfacing & programming


In this section, interfacing of ADC0804, ADC0808, ADC0848 and MAX1112 ADCs with
8051 is discussed.

13.1.1 WAP to read potentiometer output using ADC0804 and display it on LCD

The ADC0804 device is CMOS 8-bit successive approximation converters (ADC) that use a
differential potentiometric ladder for analog to digital conversion. It has only one analog channel
and if multiple analog signals need to be processed, a multiplexer can be used for selecting the
channel.

LCD
8051
P1.0 P0.7 D7
P1.1 P0.6 D6
P1.2 P0.5 D5
P1.3 P0.4 D4
P1.4 P0.3 D3
P1.5 P0.2 D2
P1.6 P0.1 D1
P1.7 P0.0 D0
P2.7 E
P3.3
RW
P3.4
P2.6 RS
VEE
VCC
10 k
GND

Figure: ADC0804 Interfacing with 8051

147
E EQU P2.7 #include<reg51.h>
RS EQU P2.6 sbit E=P2^7;
LCD EQU P0 sbit RS=P2^6;
ADC_DATA EQU P1 sfr LCD=0x80; //P0
ADC_WR EQU P3.3 sbit ADC_WR=P3^3;
ADC_INTR EQU P3.4 sbit ADC_INTR=P3^4;
ORG 00H sfr ADC_DATA=0x90; //P1
ACALL LCD_INIT
MOV ADC_DATA,#0FFH ;port=input void delay();
BACK: CLR ADC_WR ;start conversion void lcd_init();
SETB ADC_WR void lcd_command(unsigned char cmd);
HERE: ;wait for conversion void lcd_data(unsigned char dat);
JB ADC_INTR,HERE void main(){
MOV A,ADC_DATA ;read the data unsigned char adc_val,i;
MOV R4, #80H ;convert to ASCII lcd_init();
ACALL LCD_COMMAND ;display ADC_DATA=0xFF; //port = input
MOV B,#10 while(1){
DIV AB ADC_WR=0; //start conversion
MOV R3,B ADC_WR=1;
MOV B,#10 //wait for conversion and read data
DIV AB while(ADC_INTR);
ADD A,#30H adc_val=ADC_DATA;
MOV R4, A lcd_command(0x80);
ACALL LCD_DATA lcd_data(adc_val%10);
MOV A,B lcd_data((adc_val/10)%10);
ADD A,#30H lcd_data((adc_val/100)%10);
MOV R4, A for(i=0;i<5;i++)
ACALL LCD_DATA delay();
MOV A,R3 }
ADD A,#30H }
MOV R4, A
ACALL LCD_DATA void lcd_init(){
ACALL DELAY E=0;
ACALL DELAY RS=0;
ACALL DELAY //2 lines and 5×7 matrix
ACALL DELAY lcd_command(0x38);
ACALL DELAY delay();
SJMP BACK lcd_command(0x0C); //LCD ON
delay();
LCD_INIT: lcd_command(0x01); //LCD clear

148
CLR E delay();
CLR RS }
MOV R4, #38H ;2 lines, 5×7 matrix
ACALL LCD_COMMAND void lcd_command(unsigned char cmd){
ACALL DELAY RS=0;
MOV R4, #0CH ;LCD ON LCD=cmd;
ACALL LCD_COMMAND E=1;
ACALL DELAY delay();
MOV R4, #01H ;LCD clear E=0;
ACALL LCD_COMMAND }
ACALL DELAY
RET void lcd_data(unsigned char dat){
RS=1;
LCD_COMMAND: ;Function for command LCD=dat;
CLR RS E=1;
MOV LCD, R4 delay();
SETB E E=0;
ACALL DELAY }
CLR E
RET void delay(){
unsigned int val;
LCD_DATA: ;Function for LCD data for(val=0;val<40000;val++);
SETB RS }
MOV LCD, R4
SETB E
ACALL DELAY
CLR E
RET

DELAY: ;Function for delay


MOV R7, #200
LOOP1: MOV R6, #200
LOOP: DJNZ R6, LOOP
DJNZ R7, LOOP1
RET
END

149
13.1.2 WAP to read potentiometer output using ADC0808/0809 connected on channel 1
and display it on LCD

The ADC0808, ADC0809 data acquisition component is a monolithic CMOS device with
an 8-bit analog-to-digital converter, 8-channel multiplexer and microprocessor compatible
control logic. The 8-bit uses successive approximation as the conversion technique. It has
8 analog channels which can be selected from select lines A, B and C.

LCD
ADC0808 8051
DATA (D0-D7) P1.0-P1.7 P0.7 D7
ADC_SC P3.3 P0.6 D6
ADC_EOC P3.4 P0.5 D5
IN_0 ADC_A P3.5 P0.4 D4
ADC_B P3.6 P0.3 D3
ADC_C P3.7 P0.2 D2
ADC_ALE P2.0 P0.1 D1
P0.0 D0
P2.7 E
RW
P2.6 RS
VEE
VCC
10 k
GND

Figure: ADC0808 Interfacing with 8051

E EQU P2.7 #include<reg51.h>


RS EQU P2.6 sbit E=P2^7;
LCD EQU P0 sbit RS=P2^6;
ADC_DATA EQU P1 sfr LCD=0x80; //P0
ADC_SC EQU P3.3 sbit ADC_SC=P3^3;
ADC_EOC EQU P3.4 sbit ADC_EOC=P3^4;
ADC_C EQU P3.7 sbit ADC_C=P3^7;
ADC_B EQU P3.6 sbit ADC_B=P3^6;
ADC_A EQU P3.5 sbit ADC_A=P3^5;
ADC_ALE EQU P2.0 sbit ADC_ALE=P2^0;
ORG 00H sfr ADC_DATA=0x90; //P1
ACALL LCD_INIT
MOV ADC_DATA,#0FFH;port = input void delay();

150
CLR ADC_ALE void lcd_init();
CLR ADC_SC void lcd_command(unsigned char cmd);
BACK: void lcd_data(unsigned char dat);
SETB ADC_C ;channel 1 of ADC
CLR ADC_B void main(){
CLR ADC_A unsigned char adc_val,i;
SETB ADC_ALE lcd_init();
SETB ADC_SC ADC_DATA=0xFF; //port = input
CLR ADC_ALE ADC_ALE=0;
CLR ADC_SC ADC_SC=0;
HERE: JB ADC_EOC,HERE while(1){
HERE1: ;wait for conversion ADC_C=1;//channel 1 of ADC
JNB ADC_EOC,HERE1 ADC_B=0;
MOV A,ADC_DATA ;read the data ADC_A=0;
MOV R4, #80H ;convert to ASCII ADC_ALE=1;
ACALL LCD_COMMAND ;display ADC_SC=1;
MOV B,#10 ADC_ALE=0;
DIV AB ADC_SC=0;
MOV R3,B //wait for conversion and read data
MOV B,#10 while(ADC_EOC==1);
DIV AB while(ADC_EOC==0);
ADD A,#30H adc_val=ADC_DATA;
MOV R4, A lcd_command(0x80);
ACALL LCD_DATA lcd_data(adc_val%10);
MOV A,B lcd_data((adc_val/10)%10);
ADD A,#30H lcd_data((adc_val/100)%10);
MOV R4, A for(i=0;i<5;i++)
ACALL LCD_DATA delay();
MOV A,R3 }
ADD A,#30H }
MOV R4, A
ACALL LCD_DATA void lcd_init(){
ACALL DELAY E=0;
SJMP BACK RS=0;
//2 lines and 5×7 matrix
LCD_INIT: lcd_command(0x38);
CLR E delay();
CLR RS lcd_command(0x0C); //LCD ON
MOV R4, #38H ;2 lines and 5×7 matrix delay();
ACALL LCD_COMMAND lcd_command(0x01); //LCD clear

151
ACALL DELAY delay();
MOV R4, #0CH ;LCD ON, Cursor OFF }
ACALL LCD_COMMAND
ACALL DELAY
MOV R4, #01H ;LCD clear void lcd_command(unsigned char cmd){
ACALL LCD_COMMAND RS=0;
ACALL DELAY LCD=cmd;
RET E=1;
delay();
LCD_COMMAND: ;Function for command E=0;
CLR RS }
MOV LCD, R4
SETB E void lcd_data(unsigned char dat){
ACALL DELAY RS=1;
CLR E LCD=dat;
RET E=1;
delay();
LCD_DATA: ;Function for LCD data E=0;
SETB RS }
MOV LCD, R4
SETB E void delay(){
ACALL DELAY unsigned int val;
CLR E for(val=0;val<40000;val++);
RET }

DELAY: ;Function for delay


MOV R7, #200
LOOP1: MOV R6, #200
LOOP: DJNZ R6, LOOP
DJNZ R7, LOOP1
RET
END

13.1.3 WAP to read potentiometer output using ADC0848 connected on channel 1 and
display it on LCD
The ADC0844 and ADC0848 are CMOS 8-bit successive approximation A/D converters
with versatile analog input multiplexers. The 4-channel or 8-channel multiplexers can be
software configured for single-ended, differential or pseudo-differential modes of
operation.

152
LCD
ADC0848 8051
DATA (D0-D7) P1.0-P1.7 P0.7 D7
P0.6 D6
P0.5 D5
IN_0 P0.4 D4
ADC_WR P3.3 P0.3 D3
ADC_INTR P3.4 P0.2 D2
P0.1 D1
P0.0 D0
P2.7 E
RW
P2.6 RS
VEE
VCC
10 k
GND

Figure: LM35 Interfacing with 8051 using ADC0848

E EQU P2.7 #include<reg51.h>


RS EQU P2.6 sbit E=P2^7;
LCD EQU P0 sbit RS=P2^6;
ADC_DATA EQU P1 sfr LCD=0x80; //P0
ADC_WR EQU P3.3 sbit ADC_WR=P3^3;
ADC_INTR EQU P3.4 sbit ADC_INTR=P3^4;
ORG 00H sfr ADC_DATA=0x90; //P1
ACALL LCD_INIT
SETB ADC_INTR void delay();
SETB ADC_WR void lcd_init();
BACK: MOV ADC_DATA,#09H void lcd_command(unsigned char cmd);
;channel 1 of ADC void lcd_data(unsigned char dat);
CLR ADC_WR
SETB ADC_WR void main(){
MOV ADC_DATA,#0FFH unsigned char adc_val,i;
HERE: JB ADC_INTR,HERE ;wait for lcd_init();
end of conversion ADC_INTR=1;
MOV A,ADC_DATA ;read the data ADC_WR=1;
MOV R4, #80H ;convert to ASCII while(1){
ACALL LCD_COMMAND ;display //channel 1 of ADC
MOV B,#10 ADC_DATA=0x09;
DIV AB ADC_WR=0;

153
MOV R3,B ADC_WR=1;
MOV B,#10 ADC_DATA=0xFF;
DIV AB //wait for conversion and read data
ADD A,#30H while(ADC_INTR==1);
MOV R4, A adc_val=ADC_DATA;
ACALL LCD_DATA lcd_command(0x80);
MOV A,B lcd_data(adc_val%10);
ADD A,#30H lcd_data((adc_val/10)%10);
MOV R4, A lcd_data((adc_val/100)%10);
ACALL LCD_DATA for(i=0;i<5;i++)
MOV A,R3 delay();
ADD A,#30H }
MOV R4, A }
ACALL LCD_DATA
ACALL DELAY void lcd_init(){
SJMP BACK E=0;
RS=0;
LCD_INIT: //2 lines and 5×7 matrix
CLR E lcd_command(0x38);
CLR RS delay();
MOV R4, #38H ;2 lines and 5×7 matrix lcd_command(0x0C); //LCD ON
ACALL LCD_COMMAND delay();
ACALL DELAY lcd_command(0x01); //LCD clear
MOV R4, #0CH ;LCD ON, Cursor OFF delay();
ACALL LCD_COMMAND }
ACALL DELAY
MOV R4, #01H ;LCD clear
ACALL LCD_COMMAND void lcd_command(unsigned char cmd){
ACALL DELAY RS=0;
RET LCD=cmd;
E=1;
LCD_COMMAND: ;Function for command delay();
CLR RS E=0;
MOV LCD, R4 }
SETB E
ACALL DELAY void lcd_data(unsigned char dat){
CLR E RS=1;
RET LCD=dat;
E=1;
LCD_DATA: ;Function for LCD data delay();

154
SETB RS E=0;
MOV LCD, R4 }
SETB E
ACALL DELAY void delay(){
CLR E unsigned int val;
RET for(val=0;val<40000;val++);
}
DELAY: ;Function for delay
MOV R7, #200
LOOP1: MOV R6, #200
LOOP: DJNZ R6, LOOP
DJNZ R7, LOOP1
RET
END

13.1.4 WAP to read potentiometer output using MAX1112 connected on channel 1 and
display it on LCD
The MAX1112 is low-power, 8-bit, 8-channel analog-to-digital converter (ADC) which
feature an internal track/hold, voltage reference, clock, and serial interface. There are 8
analog channels which can be selected through address given in the serial comunication.

Figure: MAX1112 Interfacing with 8051

E EQU P2.7 #include<reg51.h>


RS EQU P2.6 sbit E=P2^7;
LCD EQU P0 sbit RS=P2^6;
ADC_DIN EQU P3.4 sfr LCD=0x80; //P0

155
ADC_DOUT EQU P3.6 sbit ADC_DIN=P3^4;
ADC_SCLK EQU P3.5 sbit ADC_DOUT=P3^6;
ORG 00H sbit ADC_SCLK=P3^5;
ACALL LCD_INIT sbit ACC_MBIT=ACC^7;
BACK: MOV A,#9EH ;channel 1 of ADC sbit ACC_LBIT=ACC^0;
MOV R3,#8
CTRL_WORD: RLC A ;sending bits void delay();
MOV ADC_DIN,C void lcd_init();
CLR ADC_SCLK void lcd_command(unsigned char cmd);
ACALL DELAY void lcd_data(unsigned char dat);
SETB ADC_SCLK
ACALL DELAY void main(){
DJNZ R3,CTRL_WORD unsigned char i,count;
CLR ADC_SCLK lcd_init();
SETB ADC_DOUT while(1){
SETB ADC_SCLK ;rec adc data bits ACC=0x9E;//channel 1 of ADC
ACALL DELAY //sending bits
CLR ADC_SCLK for(count=0;count<8;count++){
ACALL DELAY ADC_DIN=ACC_MBIT;
MOV R3,#8 ADC_SCLK=0;
ADC_DATA: SETB ADC_SCLK delay();
ACALL DELAY ADC_SCLK=1;
CLR ADC_SCLK delay();
ACALL DELAY ACC=ACC<<1;
MOV C,ADC_DOUT }
RLC A ADC_SCLK=0;
DJNZ R3,ADC_DATA ADC_DOUT=1;
MOV R4, #80H ;convert to ASCII //receiving adc data bits
ACALL LCD_COMMAND ;display ADC_SCLK=1;
MOV B,#10 delay();
DIV AB ADC_SCLK=0;
MOV R3,B delay();
MOV B,#10 for(count=0;count<8;count++){
DIV AB ADC_SCLK=1;
ADD A,#30H delay();
MOV R4, A ADC_SCLK=0;
ACALL LCD_DATA delay();
MOV A,B ACC=ACC<<1;
ADD A,#30H ACC_LBIT=ADC_DOUT;
MOV R4, A }

156
ACALL LCD_DATA lcd_command(0x80);
MOV A,R3 lcd_data(ACC%10);
ADD A,#30H lcd_data((ACC/10)%10);
MOV R4, A lcd_data((ACC/100)%10);
ACALL LCD_DATA for(i=0;i<5;i++)
ACALL DELAY delay();
SJMP BACK }
}
LCD_INIT:
CLR E void lcd_init(){
CLR RS E=0;
MOV R4, #38H ;2 lines and 5×7 matrix RS=0;
ACALL LCD_COMMAND //2 lines and 5×7 matrix
ACALL DELAY lcd_command(0x38);
MOV R4, #0CH ;LCD ON, Cursor OFF delay();
ACALL LCD_COMMAND lcd_command(0x0C); //LCD ON
ACALL DELAY delay();
MOV R4, #01H ;LCD clear lcd_command(0x01); //LCD clear
ACALL LCD_COMMAND delay();
ACALL DELAY }
RET

LCD_COMMAND: ;Function for command void lcd_command(unsigned char cmd){


CLR RS RS=0;
MOV LCD, R4 LCD=cmd;
SETB E E=1;
ACALL DELAY delay();
CLR E E=0;
RET }

LCD_DATA: ;Function for LCD data void lcd_data(unsigned char dat){


SETB RS RS=1;
MOV LCD, R4 LCD=dat;
SETB E E=1;
ACALL DELAY delay();
CLR E E=0;
RET }

DELAY: ;Function for delay void delay(){


MOV R7, #200 unsigned int val;

157
LOOP1: MOV R6, #200 for(val=0;val<40000;val++);
LOOP: DJNZ R6, LOOP }
DJNZ R7, LOOP1
RET
END

13.2Analog Sensor Interfacing with 8051


13.2.1 WAP to read temperature from LM35 using ADC0848 connected on channel 1 and
display it on LCD

Figure: LM35 Interfacing with 8051 using ADC0848

E EQU P2.7 #include<reg51.h>


RS EQU P2.6 sbit E=P2^7;
LCD EQU P0 sbit RS=P2^6;
ADC_DATA EQU P1 sfr LCD=0x80; //P0
ADC_WR EQU P3.3 sbit ADC_WR=P3^3;
ADC_INTR EQU P3.4 sbit ADC_INTR=P3^4;
ORG 00H
sfr ADC_DATA=0x90; //P1
SETB ADC_INTR
SETB ADC_WR
BACK: MOV ADC_DATA,#09H void delay();
;channel 1 of ADC void lcd_init();
CLR ADC_WR void lcd_command(unsigned char cmd);
SETB ADC_WR void lcd_data(unsigned char dat);
MOV ADC_DATA,#0FFH

158
HERE: ;wait for conversion void main(){
JB ADC_INTR,HERE unsigned char adc_val,i;
MOV A,ADC_DATA ;read the data lcd_init();
RLC A ;convert to temperature ADC_INTR=1;
ADD A,#2 ADC_WR=1;
MOV R4, #80H ;display while(1){
ACALL LCD_COMMAND
//channel 1 of ADC
MOV B,#10
ADC_DATA=0x09;
DIV AB
MOV R3,B ADC_WR=0;
MOV B,#10 ADC_WR=1;
DIV AB ADC_DATA=0xFF;
ADD A,#30H //wait for end of conversion and read data
MOV R4, A while(ADC_INTR==1);
ACALL LCD_DATA adc_val=ADC_DATA;
MOV A,B //convert to temperature
ADD A,#30H adc_val=adc_val*2+2;
MOV R4, A lcd_command(0x80); //display
ACALL LCD_DATA lcd_data(adc_val%10);
MOV A,R3 lcd_data((adc_val/10)%10);
ADD A,#30H
lcd_data((adc_val/100)%10);
MOV R4, A
for(i=0;i<5;i++)
ACALL LCD_DATA
ACALL DELAY delay();
SJMP BACK }
}
LCD_INIT:
CLR E void lcd_init(){
CLR RS E=0;
MOV R4, #38H ;2 lines and 5×7 RS=0;
matrix //2 lines and 5×7 matrix
ACALL LCD_COMMAND lcd_command(0x38);
ACALL DELAY delay();
MOV R4, #0CH ;LCD ON, Cursor lcd_command(0x0C); //LCD ON
OFF delay();
ACALL LCD_COMMAND lcd_command(0x01); //LCD clear
ACALL DELAY delay();
MOV R4, #01H ;LCD clear }
ACALL LCD_COMMAND
ACALL DELAY
RET void lcd_command(unsigned char cmd){
RS=0;

159
LCD_COMMAND: ;Function for LCD=cmd;
command E=1;
CLR RS delay();
MOV LCD, R4 E=0;
SETB E }
ACALL DELAY
CLR E void lcd_data(unsigned char dat){
RET RS=1;
LCD=dat;
LCD_DATA: ;Function for LCD data E=1;
SETB RS delay();
MOV LCD, R4 E=0;
SETB E }
ACALL DELAY
CLR E void delay(){
RET unsigned int val;
for(val=0;val<40000;val++);
DELAY: ;Function for delay }
MOV R7, #200
LOOP1: MOV R6, #200 void delay(){
LOOP: DJNZ R6, LOOP unsigned int val;
DJNZ R7, LOOP1 for(val=0;val<40000;val++);
RET }
END

13.2.2 WAP to change the speed of the DC fan using PWM according to the room
temperature using LM35 connected to channel 3 of ADC0808. (3 speed levels with
10%, 60% and 100% duty cycle and 28,32,36 as threshold temperature for them)

ADC0808 8051
VCC
DATA (D0-D7) P1.0-P1.7
ADC_SC P3.3
ADC_EOC P3.4
IN_3 ADC_A P3.5
ADC_B P3.6
ADC_C P3.7 P2.0
ADC_ALE 1K
P3.2

160
Figure: LM35 Interfacing with 8051 using ADC0808

FAN_PIN EQU P2.0 #include<reg51.h>


ADC_DATA EQU P1 sbit FAN_PIN=P2^0;
ADC_SC EQU P3.3 sbit ADC_SC=P3^3;
ADC_EOC EQU P3.4 sbit ADC_EOC=P3^4;
ADC_C EQU P3.7 sbit ADC_C=P3^7;
ADC_B EQU P3.6 sbit ADC_B=P3^6;
ADC_A EQU P3.5
sbit ADC_A=P3^5;
ADC_ALE EQU P2.0
sbit ADC_ALE=P2^0;
ORG 00H
;port=input sfr ADC_DATA=0x90; //P1
MOV ADC_DATA,#0FFH void delay();
CLR ADC_ALE void lcd_init();
CLR ADC_SC void lcd_command(unsigned char cmd);
BACK: void lcd_data(unsigned char dat);
SETB ADC_C ;channel 1 of ADC void main(){
CLR ADC_B unsigned char adc_val,i,duty_cycle;
CLR ADC_A ADC_DATA=0xFF; // port = input
SETB ADC_ALE ADC_ALE=0;
SETB ADC_SC ADC_SC=0;
CLR ADC_ALE while(1){
CLR ADC_SC
ADC_C=1; //channel 1 of ADC
HERE: ;wait for conversion
ADC_B=0;
JB ADC_EOC,HERE
HERE1: JNB ADC_EOC,HERE1 ADC_A=0;
MOV A,ADC_DATA ;read the data ADC_ALE=1;
CLR C ADC_SC=1;
RLC A ;convert to temperature ADC_ALE=0;
ADD A,#2 ADC_SC=0;
MOV R3,A //wait for end of conversion and read data
CLR C while(ADC_EOC==1);
SUBB A,#28 ;check temp range while(ADC_EOC==0);
JNC NEXT ;duty cycle adc_val=ADC_DATA;
MOV R0,#1 //convert to temperature
SJMP PWM
adc_val=adc_val*2+2;
NEXT: CLR C
if(adc_val<28) //check temp range
MOV A,R3
duty_cycle=1; //duty cycle
SUBB A,#32
JNC NEXT1 else if(adc_val<32)
MOV R0,#10 duty_cycle=10;
SJMP PWM else if(adc_val<36)
NEXT1: CLR C duty_cycle=60;

161
MOV A,R3 else
SUBB A,#36 duty_cycle=100;
JNC NEXT2 FAN_PIN=1;//PWM speed control
MOV R0,#60 for(i=0;i<duty_cycle;i++);
SJMP PWM FAN_PIN=0;
NEXT2: MOV R0,#99 for(i=0;i<100-duty_cycle;i++);
PWM: MOV A,#100 ;PWM speed control
}
CLR C
}
SUBB A,R0
MOV R1,A
SETB FAN_PIN
HERE2: DJNZ R0,HERE2
CLR FAN_PIN
HERE3: DJNZ R1,HERE3
AJMP BACK
END

13.2.3 WAP to turn ON 4 LEDs depending on room light intensity level using ADC0804
through channel 0 of CD74HC4052.

VCC
8051
VCC P1.0
P1.1
220 ohm
P1.2
LDR CD74HC4052
P1.3
VCC
P1.4 P1.0
OUT A0
P1.5 P1.1
GND A1
P1.6 P1.2
A2 AN
P1.7 P1.3
A3
S1 S0 P3.3
P3.4
P3.5
P3.6

Figure: LDR Interfacing with 8051 using ADC0804 (with multiplexer)

ADC_DATA EQU P1 #include<reg51.h>


ADC_WR EQU P3.3 sbit ADC_WR=P3^3;
ADC_INTR EQU P3.4 sbit ADC_INTR=P3^4;
MUX_SL1 EQU P3.6 sfr ADC_DATA=0x90; //P1
MUX_SL0 EQU P3.5 sbit MUX_SL1=P3^6;
LED1 EQU P1.0 sbit MUX_SL0=P3^5;
LED2 EQU P1.1
sbit LED1=P1^0;
LED3 EQU P1.2
sbit LED2=P1^1;
LED4 EQU P1.3
ORG 00H sbit LED3=P1^2;

162
MOV P1,#0FFH ;P1 = input sbit LED4=P1^3;
CLR MUX_SL1 ;MUX channel 0
CLR MUX_SL0 void main(){
AGAIN: ;L-to-H to start conversion unsigned char adc_val;
CLR ADC_WR ADC_DATA=0xFF; // port = input
SETB ADC_WR MUX_SL1=0;
HERE: ;wait for end of conversion
MUX_SL0=0;
JB ADC_INTR,HERE
while(1){
MOV R0,ADC_DATA ;read data
MOV A,R0 ;check range //L-to-H to start conversion
CLR C ADC_WR=0;
SUBB A,#51 ADC_WR=1;
JC L4 //wait for end of conversion and read data
MOV A,R0 while(ADC_INTR);
CLR C adc_val=ADC_DATA;
SUBB A,#102 if(adc_val<51){ //check range
JC L3 //glow LEDs acc to light level
MOV A,R0 LED1=1;
CLR C LED2=1;
SUBB A,#153 LED3=1;
JC L2
LED4=1;
MOV A,R0
}
CLR C
SUBB A,#204 else if(adc_val<102){
JC L1 LED1=0;
OFF: ;glow LEDs acc to light level LED2=1;
SETB LED1 LED3=1;
SETB LED2 LED4=1;
SETB LED3 }
SETB LED4 else if(adc_val<153){
AJMP AGAIN LED1=0;
L1: CLR LED1 LED2=0;
SETB LED2 LED3=1;
SETB LED3
LED4=1;
SETB LED4
}
AJMP AGAIN
else if(adc_val<204){
L2: CLR LED1
CLR LED2 LED1=0;
SETB LED3 LED2=0;
SETB LED4 LED3=0;
AJMP AGAIN LED4=1;
L3: CLR LED1 }
CLR LED2 else{

163
CLR LED3 LED1=0;
SETB LED4 LED2=0;
AJMP AGAIN LED3=0;
L4: CLR LED1 LED4=0;
CLR LED2 }
CLR LED3 }
CLR LED4
}
AJMP AGAIN
END

13.2.4 WAP to show the alcohol intake level of a person through 4 LEDs (use channel 1 of
MAX1112)

Figure: Alcohol Sensor Interfacing with 8051 using MAX1112

ADC_DIN EQU P3.4 #include<reg51.h>


ADC_DOUT EQU P3.6 sbit ADC_DIN=P3^4;
ADC_SCLK EQU P3.5 sbit ADC_DOUT=P3^6;
LED1 EQU P1.0 sbit ADC_SCLK=P3^5;
LED2 EQU P1.1 sbit ACC_MBIT=ACC^7;
LED3 EQU P1.2 sbit ACC_LBIT=ACC^0;
LED4 EQU P1.3 sbit LED1=P1^0;
ORG 00H sbit LED2=P1^1;
AGAIN: ;select channel 1 of ADC sbit LED3=P1^2;
MOV A,#9EH sbit LED4=P1^3;
MOV R3,#8
CTRL_WORD: RLC A ;sending bits void delay();
MOV ADC_DIN,C
CLR ADC_SCLK void main(){
ACALL DELAY unsigned char count,adc_val;
SETB ADC_SCLK while(1){

164
ACALL DELAY //select channel 1 of ADC
DJNZ R3,CTRL_WORD ACC=0x9E;
CLR ADC_SCLK //sending bits
SETB ADC_DOUT for(count=0;count<8;count++){
;receiving adc data bits ADC_DIN=ACC_MBIT;
SETB ADC_SCLK ADC_SCLK=0;
ACALL DELAY delay();
CLR ADC_SCLK ADC_SCLK=1;
ACALL DELAY delay();
MOV R3,#8 ACC=ACC<<1;
ADC_DATA: SETB ADC_SCLK }
ACALL DELAY ADC_SCLK=0;
CLR ADC_SCLK ADC_DOUT=1;
ACALL DELAY //receiving adc data bits
MOV C,ADC_DOUT ADC_SCLK=1;
RLC A delay();
DJNZ R3,ADC_DATA ADC_SCLK=0;
delay();
MOV R0,A ;check level for(count=0;count<8;count++){
CLR C ADC_SCLK=1;
SUBB A,#51 delay();
JC L4 ADC_SCLK=0;
MOV A,R0 delay();
CLR C ACC=ACC<<1;
SUBB A,#102 ACC_LBIT=ADC_DOUT;
JC L3 }
MOV A,R0 adc_val=ACC;
CLR C if(adc_val<51){ //check range
SUBB A,#153 //glow LEDs acc to light level
JC L2 LED1=1;
MOV A,R0 LED2=1;
CLR C LED3=1;
SUBB A,#204 LED4=1;
JC L1 }
OFF: ;show level using LEDs else if(adc_val<102){
SETB LED1 LED1=0;
SETB LED2 LED2=1;
SETB LED3 LED3=1;
SETB LED4 LED4=1;
AJMP AGAIN }

165
L1: CLR LED1 else if(adc_val<153){
SETB LED2 LED1=1;
SETB LED3 LED2=0;
SETB LED4 LED3=1;
AJMP AGAIN LED4=1;
L2: SETB LED1 }
CLR LED2 else if(adc_val<204){
SETB LED3 LED1=1;
SETB LED4 LED2=1;
AJMP AGAIN LED3=0;
L3: SETB LED1 LED4=1;
SETB LED2 }
CLR LED3 else{
SETB LED4 LED1=1;
AJMP AGAIN LED2=1;
L4: SETB LED1 LED3=1;
SETB LED2 LED4=0;
SETB LED3 }
CLR LED4 }
AJMP AGAIN }
ACALL DELAY
ACALL DELAY void delay(){
ACALL DELAY unsigned int val;
ACALL DELAY for(val=0;val<40000;val++);
ACALL DELAY }
AJMP AGAIN

DELAY: ;Function for delay


MOV R7, #200
LOOP1: MOV R6, #200
LOOP: DJNZ R6, LOOP
DJNZ R7, LOOP1
RET
END

13.3DAC interfacing with 8051


In this section, interfacing of DAC0808 will be discussed. The DAC0808 is an 8-bit
monolithic digital-to-analog converter (DAC). The DAC0808 will interface directly with
popular TTL, DTL or CMOS logic levels chips such as 8051 microcontroller with any 8-
bit port. Its interfacing with 8051 is shown in below figure.

166
8051

P1.0
P1.1
P1.2
P1.3
P1.4
P1.5
P1.6
P1.7

Figure: DAC0808 Interfacing with 8051

13.3.1 WAP to generate a triangular wave using DAC0808/MC1408


DAC EQU P1 #include<reg51.h>
ORG 00H sfr DAC=0x90; //P1
MOV A,#0 void main(){
UP: MOV DAC,A ;0 to 255 int i;
INC A while(1){
CJNE A,#255,UP for(i=0;i<256;i++) //0 to 255
DOWN: MOV DAC,A ;255 to 0 DAC=i;
DEC A for(i=255;i>=0;i--) //255 to 0
CJNE A,#0,DOWN DAC=i;
SJMP UP }
END }

13.3.2 WAP to generate a staircase wave with 5 steps using DAC0808/MC1408


DAC EQU P1 #include<reg51.h>
ORG 00H sfr DAC=0x90; //P1
MOV A,#0 void delay();
STAIR: MOV DAC,A void main(){
ACALL DELAY int i;
RPT: ADD A,#51 ;next step while(1){ //5-steps of 251
MOV DAC,A for(i=0;i<256;i=i+51){
ACALL DELAY DAC=i;
CJNE A,#255, RPT delay();

167
SJMP STAIR }
}
DELAY: ;Function for delay }
MOV R7, #200
LOOP1: MOV R6, #200 void delay(){
LOOP: DJNZ R6, LOOP unsigned int i;
DJNZ R7, LOOP1 for(i=0;i<4000;i++);
RET }
END

168
CHAPTER 14
External Data Memory Interfacing with 8051
External Data Memory can be interfaced with 8051 using port 0 and port 2. Port 0 has additional
functionality of 8-bit data bus and port 2 combined with port 0 have functionality of 16-bit address
bus. So, external memory and/or I/O device with maximum 2^16 addresses can be accessed using
port 2 and port 0. Port 0 is multiplexed between lower 8-bit address and data. A latch is used to
demultiplex the address and the data.
In assembly language, The MOVX instruction transfers data between the accumulator and external
data memory. External memory may be addressed via 16-bits in the DPTR register or via 8-bits in
the R0 or R1 registers. When using 8-bit addressing, Port 2 must contain the high-order byte of
the address. For example, MOVX A, @DPTR will transfer the data from external memory on
address contained in DPTR to accumulator. In C, XBYTE instruction is used for the same, which
is defined in absacc.h file.

14.1Read characters from an external data memory (ROM) and display on LCD

Interfacing Diagram:

LCD
8051
P1.7 D7
VCC
ROM P1.6 D6
VCC D7-0 P0 P1.5 D5
LATCH
A7-0 P1.4
ALE D4
ALE P1.3 D3
CS A15-8 P2 P1.2 D2
GND RD RD P1.1 D1
P1.0 D0
P3.7 E
P2.5 RW
P2.6 RS
VEE
VCC
10 k
GND

169
Assembly Embedded C

E EQU P3.5 #include<reg51.h>


RS EQU P3.4 #include<absacc.h>
LCD EQU P1 sbit E=P3^5;
ORG 00H sbit RS=P3^4;
ACALL LCD_INIT sfr LCD=0x90; //P1
MAIN:
MOV DPTR,#8192 ;start address void main(){
MOV R0,#8 ;count for number of unsigned char val,i;
bytes LCD_init();
MOV R4, #01H for(i=0;i<5;i++){
ACALL LCD_COMMAND LCD_command(0x01);
NEXT: CLR A val=XBYTE[i]; //fetch bytes
MOVX A,@DPTR ;fetch bytes LCD_BIN3(val);
INC DPTR ;next bytes }
MOV B,#10 ;convert to ASCII }
DIV AB ;and display on LCD
MOV R3,B void lcd_init(){
MOV B,#10 E=0;
DIV AB RS=0;
ADD A,#30H //2 lines and 5×7 matrix
MOV R4, A lcd_command(0x38);
ACALL LCD_DATA delay();
MOV A,B lcd_command(0x0C); //LCD ON
ADD A,#30H delay();
MOV R4, A lcd_command(0x01); //LCD clear
ACALL LCD_DATA delay();
MOV A,R3 }
ADD A,#30H
MOV R4, A void lcd_command(unsigned char cmd){
ACALL LCD_DATA RS=0;
ACALL DELAY LCD=cmd;
DJNZ R0,NEXT E=1;
HERE: SJMP HERE delay();
E=0;
LCD_INIT: }
CLR E
CLR RS void lcd_data(unsigned char dat){
MOV R4, #38H ;2 lines, 5×7 matrix RS=1;
ACALL LCD_COMMAND LCD=dat;

170
ACALL DELAY E=1;
MOV R4, #0CH ;LCD ON delay();
ACALL LCD_COMMAND E=0;
ACALL DELAY }
MOV R4, #01H ;LCD clear
ACALL LCD_COMMAND void delay(){
ACALL DELAY unsigned int val;
RET for(val=0;val<40000;val++);
}
LCD_COMMAND: ;Function for command
CLR RS
MOV LCD, R4
SETB E
ACALL DELAY
CLR E
RET

LCD_DATA: ;Function for LCD data


SETB RS
MOV LCD, R4
SETB E
ACALL DELAY
CLR E
RET

DELAY: ;Function for delay


MOV R7, #200
LOOP1: MOV R6, #200
LOOP: DJNZ R6, LOOP
DJNZ R7, LOOP1
RET
END

171
CHAPTER 15

Extending ports using 8255 PPI


The 8255 is a 40-pin DIP chip with three separately accessible ports. The ports are each 8-bit,
and are named A, B, and C. The individual ports of the 8255 can be programmed to be input
or output and can be changed dynamically. In addition, 8255 ports, have handshaking
capability, thereby allowing interface with devices that also have handshaking signals, such as
printers.

Figure16.5 : 8255 PPI


Pin functions:
PAO – PA7: The 8-bit port A can be programmed as all input, or as all output, or all bits as
bidirectional input/output.
PBO – PB7: The 8-bit port B can be programmed as all input or as all output. Port B cannot
be used as a bidirectional port.
PCO-PC7: This 8-bit port C can be all input or all output. It can also be split into two parts,
CU (upper bits PC4 – PC7) and CL (lower bits PCO – PC3). Each can be used for input or
output.
RD and WR: These two active-low control signals are inputs to the 8255. The RD and WR
signals from the 8031/51 are connected to these inputs.
DO – D7 data pin: The data pins of the 8255 are connected to the data pins of the
microcontroller allowing it to send data back and forth between the controller and the 8255
chip.
Reset: This is an active-high signal input into the 8255 used to clear the control register. When
RESET is activated, all ports are initialized as input ports. In many designs this pin is connected
to the RESET output of the system bus or grounded to make it inactive. Like all 1C input pins,
it should not be left unconnected.

172
AO,A1, and CS: While CS (chip select) selects the entire chip, it is AO and Al that select
specific ports. These three pins are used to access ports A, B, C, or the control register. Note
that CS is active-low.

Mode selection of the 8255:


While ports A, B, and C are used to input or output data, it is the control register that must be
programmed to select the operation mode of the three ports. The ports of the 8255 can be
programmed in any of the following modes.
Mode 0, simple I/O mode: In this mode, any of the ports A, B, CL, and CU can be
programmed as input or output. In this mode, all bits are out or all are in. In other words, there
is no such thing as single-bit control as we have seen in PO – P3 of the 8051. Since the vast
majority of applications involving the 8255 use this simple I/O mode, we will concentrate on
this mode in this chapter.
Mode 1: In this mode, ports A and B can be used as input or output ports with handshaking
capabilities. Handshaking signals are provided by the bits of port C.
Mode 2: In this mode, port A can be used as a bidirectional I/O port with hand shaking
capabilities whose signals are provided by port C. Port B can be used either in simple I/O mode
or handshaking mode 1.
BSR (bit set/reset) mode: In this mode, only the individual bits of port C can be programmed.

15.1Read the push buttons state connected to port A and indicate on LEDs on port B of 8255
Interfacing Diagram:

VCC
8255
VCC
4.7 K
8 Push Buttons PA
VCC

8051
220 ohm
PB D0-D7 P0

LATCH
RESET A1
ALE
CS A0
ALE
GND RD RD
WR WR

173
Assembly

PB EQU 0000H ;PORTA_8255


LED EQU 0001H ;PORTB_8255
PORTC_8255 EQU 0002H ;PORTC_8255
CTRL_8255 EQU 0003H ;CTRL_8255

ORG 00H
MOV DPTR,#CTRL_8255 ;control register
MOV A,#90H ;port A=IN, port B=out
MOVX @DPTR,A
AGAIN:
MOV DPTR,#PB ;read push buttons
MOVX A,@DPTR
MOV DPTR,#LED ;indicate on LEDs
MOVX @DPTR,A
SJMP AGAIN
END

Embedded C

#include<reg51.h>
#include<absacc.h>
#define PB 0x0000 //PORTA_8255
#define LED 0x0001 //PORTB_8255
#define PORTC_8255 0x0002 //PORTC_8255
#define CTRL_8255 0x0003 //CTRL_8255

void main(){
unsigned char val;
XBYTE[CTRL_8255]=0x90; //port A=IN, port B=out
while(1){
val=XBYTE[PB]; //read push buttons
XBYTE[LED]=val; //indicate on LEDs
}
}

174
15.2WAP to generate Square wave with 50% duty cycle at port C[7] of 8255
Interfacing Diagram:
VCC
8255
VCC

PC

8051

PB D0-D7 P0

LATCH
RESET A1
ALE
CS A0
ALE
GND RD RD
WR WR

Assembly Embedded C

PORTA_8255 EQU 0001H #include<reg51.h>


PORTB_8255 EQU 0002H #include<absacc.h>
PORTC_8255 EQU 0003H ;PWM at C[7] #define PORTA_8255 0x0000
CTRL_8255 EQU 0004H ;control reg #define PORTB_8255 0x0001
ORG 00H
#define PORTC_8255 0x0002//PWM at C[7]
MOV DPTR,#CTRL_8255 ;control
#define CTRL_8255 0x0003 //control reg
register
MOV A,#80H ;port C=out
void delay();
MOVX @DPTR,A void main(){
MOV DPTR,#PORTC_8255 //port C=out
AGAIN: MOV A,#80H ;PWM at C[7] XBYTE[CTRL_8255]=0x80;
MOVX @DPTR,A while(1){
ACALL DELAY //PWM at C[7]
MOV A,#00H XBYTE[PORTC_8255]=0x80;
MOVX @DPTR,A delay();
ACALL DELAY XBYTE[PORTC_8255]=0x00;
SJMP AGAIN
delay();
}
DELAY: ;Function for delay
MOV R1, #200
}
LOOP1: MOV R2, #200
LOOP: DJNZ R2, LOOP void delay(){
DJNZ R1, LOOP1 unsigned int i;
RET for(i=0;i<10000;i++);
END }

175
15.3Display numbers from 0 to 9 on 7-segment connected at port A of 8255
Interfacing Diagram:
VCC
8255
VCC

baC fg

8
PA

8051
dp c C d e

D0-D7 P0

LATCH
RESET A1
CS A0 ALE
ALE
GND RD RD
WR WR

Assembly Embedded C

SEVSEG EQU 0001H ;PORTA #include<reg51.h>


PORTB_8255 EQU 0002H ;PORTB #include<absacc.h>
PORTC_8255 EQU 0003H ;PORTC #define SEVSEG 0x0000 //PORTA
CTRL_8255 EQU 0004H ;CTRL #define PORTB_8255 0x0001 //PORTB
ORG 00H #define PORTC_8255 0x0002 //PORTC
MOV DPTR,#CTRL_8255 #define CTRL_8255 0x0003 //CTRL_reg
MOV A,#80H ;port A=out
MOVX @DPTR,A void delay();
MOV DPTR,#SEVSEG
AGAIN: MOV A,#0E7H void main(){
;DISPLAY 0 //port A=out
MOVX @DPTR,A XBYTE[CTRL_8255]=0x80;
ACALL DELAY while(1){
MOV A,#21H ;DISPLAY 1 XBYTE[SEVSEG]=0xE7;
MOVX @DPTR,A //DISPLAY 0
ACALL DELAY delay();
MOV A,#0CBH ;DISPLAY 2 XBYTE[SEVSEG]=0x21; //1
MOVX @DPTR,A delay();

176
ACALL DELAY XBYTE[SEVSEG]=0xCB; //2
MOV A,#0ABH ;DISPLAY 3 delay();
MOVX @DPTR,A XBYTE[SEVSEG]=0xAB; //3
ACALL DELAY delay();
MOV A,#2DH ;DISPLAY 4 XBYTE[SEVSEG]=0x2D; //4
MOVX @DPTR,A delay();
ACALL DELAY XBYTE[SEVSEG]=0xAE; //5
MOV A,#0AEH ;DISPLAY 5 delay();
MOVX @DPTR,A XBYTE[SEVSEG]=0xEE; //6
ACALL DELAY delay();
MOV A,#0EEH ;DISPLAY 6 XBYTE[SEVSEG]=0x23; //7
MOVX @DPTR,A delay();
ACALL DELAY XBYTE[SEVSEG]=0xEF; //8
MOV A,#23H ;DISPLAY 7 delay();
MOVX @DPTR,A XBYTE[SEVSEG]=0xAF; //9
ACALL DELAY delay();
MOV A,#0EFH ;DISPLAY 8 }
MOVX @DPTR,A }
ACALL DELAY
MOV A,#0AFH ;DISPLAY 9 void delay(){
MOVX @DPTR,A unsigned int i;
ACALL DELAY for(i=0;i<10000;i++);
AJMP AGAIN }

DELAY:
;DELAY function
MOV R5, #10
LOOP2: MOV R6, #200
LOOP1: MOV R7, #200
LOOP: DJNZ R7, LOOP
DJNZ R6, LOOP1
DJNZ R5, LOOP2
RET
END

177
15.4Display key pressed (hex keypad), on 7-segment connected at port C and port A
respectively of 8255
Interfacing Diagram:
VCC
8255
VCC

PA
baC fg

8 8051
dp c C d e

D0-D7 P0

LATCH
RESET A1
ALE
CS A0
ALE
GND RD RD
WR WR

PC

Assembly

SEVSEG EQU 0001H ;PORTA_8255


PORTB_8255 EQU 0002H ;PORTB_8255
KEYPAD EQU 0003H ;PORTC_8255
CTRL_8255 EQU 0004H ;CTRL_8255
ORG 00H
MOV DPTR,#CTRL_8255
MOV A,#88H ;port C[7:4]=IN, C[3:0]=OUT, A=OUT
MOVX @DPTR,A
AGAIN: MOV DPTR,#KEYPAD
MOV A, #11111110B;column1=0, other columns=1
MOVX @DPTR,A
MOVX A,@DPTR
KEY_1: CJNE A,#11101110B, KEY_2 ;check all the rows and dislay on 7-segment

178
MOV A, #21H ;Display 1
MOV DPTR,#SEVSEG
AJMP AGAIN
KEY_2: CJNE A,#11011110B, KEY_3
MOV A, #0CBH ;Display 2
MOV DPTR,#SEVSEG
AJMP AGAIN
KEY_3: CJNE A,#10111110B, KEY_A
MOV A, #0ABH ;Display 3
MOV DPTR,#SEVSEG
AJMP AGAIN
KEY_A: CJNE A,#01111110B, COL_2
MOV A, #6FH ;Display A
MOV DPTR,#SEVSEG
AJMP AGAIN

COL_2: MOV DPTR,#KEYPAD


MOV A, #11111101B;column2=0, other columns=1
MOVX @DPTR,A
MOVX A,@DPTR
KEY_4: CJNE A,#11101101B, KEY_5 ;check all the rows and dislay on 7-segment
MOV A, #2DH ;Display 4 on seven segment
MOV DPTR,#SEVSEG
AJMP AGAIN
KEY_5: CJNE A,#11011101B, KEY_6
MOV A, #0AEH ;Display 5
MOV DPTR,#SEVSEG
AJMP AGAIN
KEY_6: CJNE A,#10111101B, KEY_B
MOV A, #0EEH ;Display 6
MOV DPTR,#SEVSEG
AJMP AGAIN
KEY_B: CJNE A,#01111101B, COL_3
MOV A, #0ECH ;Display B
MOV DPTR,#SEVSEG
AJMP AGAIN

COL_3: MOV DPTR,#KEYPAD


MOV A, #11111011B;column3=0, other columns=1
MOVX @DPTR,A

179
MOVX A,@DPTR
KEY_7: CJNE A,#11101011B, KEY_8 ;check all the rows and dislay on 7-segment
MOV A, #23H ;Display 7
MOV DPTR,#SEVSEG
AJMP AGAIN
KEY_8: CJNE A,#11011011B, KEY_9
MOV A, #0EFH ;Display 8
MOV DPTR,#SEVSEG
AJMP AGAIN
KEY_9: CJNE A,#10111011B, KEY_C
MOV A, #0AFH ;Display 9
MOV DPTR,#SEVSEG
AJMP AGAIN
KEY_C: CJNE A,#01111011B, COL_4
MOV A, #0C6H ;Display C
MOV DPTR,#SEVSEG
AJMP AGAIN

COL_4: MOV DPTR,#KEYPAD


MOV A, #11110111B;column4=0, other columns=1
MOVX @DPTR,A
MOVX A,@DPTR
KEY_STAR: CJNE A,#11100111B, KEY_0 ;check all the rows and dislay on 7-segment
MOV A, #4CH ;Display STAR
MOV DPTR,#SEVSEG
AJMP AGAIN
KEY_0: CJNE A,#11010111B, KEY_HASH
MOV A, #0E7H ;Display 0
MOV DPTR,#SEVSEG
AJMP AGAIN
KEY_HASH: CJNE A,#10110111B, KEY_D
MOV A, #6DH ;Display HASH
MOV DPTR,#SEVSEG
AJMP AGAIN
KEY_D: CJNE A,#01110111B, END_JUMP
MOV A, #0E9H ;Display D
MOV DPTR,#SEVSEG
END_JUMP: AJMP AGAIN
END

180
Embedded C

#include<reg51.h>
#include<absacc.h>
#define SEVSEG 0x0000 //PORTA_8255
#define PORTB_8255 0x0001 //PORTB_8255
#define KEYPAD 0x0002 //PORTC_8255
#define CTRL_8255 0x0003 //CTRL_8255

void main(){
unsigned char val;
XBYTE[CTRL_8255]=0x88; //port C[7:4]=IN, C[3:0]=OUT, A=OUT
while(1){

XBYTE[KEYPAD]=0xFE; //column1=0, other columns=1


val=XBYTE[KEYPAD];
if(val==0xEE) //check all the rows and dislay on 7-segment
XBYTE[SEVSEG]=0x21; //Display 1
else if(val==0xDE)
XBYTE[SEVSEG]=0xCB; //2
else if(val==0xBE)
XBYTE[SEVSEG]=0xAB; // 3
else if(val==0x7E)
XBYTE[SEVSEG]=0x6F; // A
XBYTE[KEYPAD]=0xFD; //column2=0, other columns=1
val=XBYTE[KEYPAD];
if(val==0xED) //check all the rows and dislay on 7-segment
XBYTE[SEVSEG]=0x2D; // 4
else if(val==0xDD)
XBYTE[SEVSEG]=0xAE; // 5
else if(val==0xBD)
XBYTE[SEVSEG]=0xEE; // 6
else if(val==0x7D)
XBYTE[SEVSEG]=0xEC; // B

XBYTE[KEYPAD]=0xFB; //column3=0, other columns=1


val=XBYTE[KEYPAD];
if(val==0xEB) //check all the rows and dislay on 7-segment
XBYTE[SEVSEG]=0x23; // 7
else if(val==0xDB)
XBYTE[SEVSEG]=0xEF; // 8

181
else if(val==0xBB)
XBYTE[SEVSEG]=0xAF; // 9
else if(val==0x7B)
XBYTE[SEVSEG]=0xC6; // C

XBYTE[KEYPAD]=0xF7; //column3=0, other columns=1


val=XBYTE[KEYPAD];
if(val==0xE7) //check all the rows and dislay on 7-segment
XBYTE[SEVSEG]=0x4C; // star
else if(val==0xD7)
XBYTE[SEVSEG]=0xE7; // 0
else if(val==0xB7)
XBYTE[SEVSEG]=0x6D; // #
else if(val==0x77)
XBYTE[SEVSEG]=0xE9; // D
}
}

15.5WAP to display hex value on seven segment and corresponding binary using LEDs
connected at port B and C[3:0] of 8255

Interfacing Diagram:
VCC
8255
VCC

PB
baC fg

8 8051
dp c C d e

D0-D7 P0

LATCH
RESET A1
ALE
CS A0
ALE
GND RD RD
WR WR
VCC

220 ohm

PC

182
Assembly Embedded C

PORTA_8255 EQU 0001H #include<reg51.h>


SEVSEG EQU 0002H ;PORTB #include<absacc.h>
LED EQU 0003H ;PORTC[3:0] #define PORTA_8255 0x0000 //PORTA
CTRL_8255 EQU 0004H #define SEVSEG 0x0001 //PORTB
ORG 00H #define LED 0x0002 //PORTC
MOV DPTR,#CTRL_8255 #define CTRL_8255 0x0003 //CTRL_reg
MOV A,#80H ;portB=OUT,C=OUT void delay();
MOVX @DPTR,A void main(){
//port B=OUT, C=OUT
AGAIN: MOV DPTR,#SEVSEG XBYTE[CTRL_8255]=0x80;
MOV A,#0E7H ;DISPLAY 0 while(1){
MOVX @DPTR,A XBYTE[SEVSEG]=0xE7;
MOV DPTR,#LED XBYTE[LED]=0xFF;
MOV A,#11111111B //DISPLAY 0
MOVX @DPTR,A delay();
ACALL DELAY XBYTE[SEVSEG]=0x21; //1
MOV DPTR,#SEVSEG XBYTE[LED]=0xFE;
MOV A,#21H ;DISPLAY 1 delay();
MOVX @DPTR,A XBYTE[SEVSEG]=0xCB; //2
MOV DPTR,#LED XBYTE[LED]=0xFD;
MOV A,#11111110B delay();
MOVX @DPTR,A XBYTE[SEVSEG]=0xAB; //3
ACALL DELAY XBYTE[LED]=0xFC;
MOV DPTR,#SEVSEG delay();
MOV A,#0CBH ;DISPLAY 2 XBYTE[SEVSEG]=0x2D; //4
MOVX @DPTR,A XBYTE[LED]=0xFB;
MOV DPTR,#LED delay();
MOV A,#11111101B XBYTE[SEVSEG]=0xAE; //5
MOVX @DPTR,A XBYTE[LED]=0xFA;
ACALL DELAY delay();
MOV DPTR,#SEVSEG XBYTE[SEVSEG]=0xEE; //6
MOV A,#0ABH ;DISPLAY 3 XBYTE[LED]=0Xf9;
MOVX @DPTR,A delay();
MOV DPTR,#LED XBYTE[SEVSEG]=0x23; //7
MOV A,#11111100B XBYTE[LED]=0xF8;
MOVX @DPTR,A delay();
ACALL DELAY XBYTE[SEVSEG]=0xEF; //8
MOV DPTR,#SEVSEG XBYTE[LED]=0xF7;

183
MOV A,#2DH ;DISPLAY 4 delay();
MOVX @DPTR,A XBYTE[SEVSEG]=0xAF; //9
MOV DPTR,#LED XBYTE[LED]=0xF6;
MOV A,#11111011B delay();
MOVX @DPTR,A XBYTE[SEVSEG]=0xAF; //A
ACALL DELAY XBYTE[LED]=0xF5;
MOV DPTR,#SEVSEG delay();
MOV A,#0AEH ;DISPLAY 5 XBYTE[SEVSEG]=0xAF; //B
MOVX @DPTR,A XBYTE[LED]=0xF4;
MOV DPTR,#LED delay();
MOV A,#11111010B XBYTE[SEVSEG]=0xAF; //C
MOVX @DPTR,A XBYTE[LED]=0xF3;
ACALL DELAY delay();
MOV DPTR,#SEVSEG XBYTE[SEVSEG]=0xAF; //D
MOV A,#0EEH ;DISPLAY 6 XBYTE[LED]=0xF2;
MOVX @DPTR,A delay();
MOV DPTR,#LED XBYTE[SEVSEG]=0xAF; //E
MOV A,#11111001B XBYTE[LED]=0xF1;
MOVX @DPTR,A delay();
ACALL DELAY XBYTE[SEVSEG]=0xAF; //F
OV DPTR,#SEVSEG XBYTE[LED]=0xF0;
MOV A,#23H ;DISPLAY 7 delay();
MOVX @DPTR,A }
MOV DPTR,#LED }
MOV A,#11111000B
MOVX @DPTR,A void delay(){
ACALL DELAY unsigned int i;
MOV DPTR,#SEVSEG for(i=0;i<40000;i++);
MOV A,#0EFH ;DISPLAY 8 }
MOVX @DPTR,A
MOV DPTR,#LED
MOV A,#11110111B
MOVX @DPTR,A
ACALL DELAY
MOV DPTR,#SEVSEG
MOV A,#0AFH ;DISPLAY 9
MOVX @DPTR,A
MOV DPTR,#LED
MOV A,#11110110B
MOVX @DPTR,A

184
ACALL DELAY
MOV DPTR,#SEVSEG
MOV A,#6FH ;DISPLAY A
MOVX @DPTR,A
MOV DPTR,#LED
MOV A,#11110101B
MOVX @DPTR,A
ACALL DELAY
MOV DPTR,#SEVSEG
MOV A,#0ECH ;DISPLAY b
MOVX @DPTR,A
MOV DPTR,#LED
MOV A,#11110100B
MOVX @DPTR,A
ACALL DELAY
MOV DPTR,#SEVSEG
MOV A,#0C6H ;DISPLAY C
MOVX @DPTR,A
MOV DPTR,#LED
MOV A,#11110011B
MOVX @DPTR,A
ACALL DELAY
MOV DPTR,#SEVSEG
MOV A,#0E9H ;DISPLAY d
MOVX @DPTR,A
MOV DPTR,#LED
MOV A,#11110010B
MOVX @DPTR,A
ACALL DELAY
MOV DPTR,#SEVSEG
MOV A,#0CEH ;DISPLAY E
MOVX @DPTR,A
MOV DPTR,#LED
MOV A,#11110001B
MOVX @DPTR,A
ACALL DELAY
MOV DPTR,#SEVSEG
MOV A,#04EH ;DISPLAY F
MOVX @DPTR,A
MOV DPTR,#LED

185
MOV A,#11110000B
MOVX @DPTR,A
ACALL DELAY
AJMP AGAIN

DELAY:
;DELAY function
MOV R5, #10
LOOP2: MOV R6, #200
LOOP1: MOV R7, #200
LOOP: DJNZ R7, LOOP
DJNZ R6, LOOP1
DJNZ R5, LOOP2
RET
END

186
CHAPTER 16
RTC Interfacing with 8051

The real-time clock (RTC) is a widely used device that provides accurate time and date for many
applications. Many systems such as the x86 IBM PC come with such a chip on the motherboard.
The RTC chip in the IBM PC provides time components of hour, minute, and second, in addition
to the date/calendar components of year, month, and day. The RTC chip uses an internal battery,
which keeps the time and date even when the power is off. Although some 8051 family members,
such as the DS5000T, come with the RTC already embedded into the chip, we have to interface
the vast majority of them to an external RTC chip. One of the most widely used RTC chips is the
DS 12887 from Dallas Semiconductor/Maxim Corp. The DS 12887 supports both 12-hour and 24-
hour clock modes with AM and PM in the 12-hour mode. The DS12887 has a total of 128 bytes
of nonvolatile RAM. It uses 14 bytes of RAM for clock/calendar and control registers, and the
other 114 bytes of RAM are for general-purpose data storage. The 14-bytes Ram is used to store
and retrieve time and date information. There are 4 control registers A, B, C and D.

Figure: DS12887 RTC Registers

16.1WRITE A PROGRAM to set the time (24-hour mode) and date on RTC DS12887 in
BCD format
Interfacing Diagram:

187
Assembly Embedded C

ORG 00H #include<reg51.h>


MOV R0,#10 ;TURN ON OSC #include<absacc.h>
MOV A,#20H
MOVX @R0,A void main(){
MOV R0,#11 ;BCD,24HRS XBYTE[10]=0x20; //TURN ON OSC
MOV A,#83H XBYTE[11]=0x83; //BCD,24HRS
MOVX @R0,A XBYTE[0]=0x00; //SET SECONDS
MOV R0,#00 ;SET SECONDS XBYTE[2]=0x30; //SET MINUTES
MOV A,#00H XBYTE[4]=0x16; //SET HOURS
MOVX @R0,A XBYTE[7]=0x12; //SET DATE
MOV R0,#02 ;SET MINUTES XBYTE[8]=0x10; //SET MONTH
MOV A,#30H XBYTE[9]=0x17; //SET YEAR
MOVX @R0,A XBYTE[3]=0x03; //B7=0 ALLOW
MOV R0,#4 ;SET HOURS UPDATE
MOV A,#16H }
MOVX @R0,A
MOV R0,#07 ;SET DAY
MOV A,#12H
MOVX @R0,A
MOV R0,#08 ;SET MONTH
MOV A,#10H
MOVX @R0,A
MOV R0,#09 ;SET YEAR
MOV A,#17H
MOVX @R0,A
;B7=0 ALLOW UPDATE
MOV R0,#03
MOV A,#03H
MOVX @R0,A
END

188
16.2WRITE A PROGRAM to read the time (24-hour mode) and date from RTC DS12887
(BCD format) and display on LCD
Interfacing Diagram:

Assembly Embedded C

ORG 00H #include<reg51.h>


ACALL LCD_INIT #include<absacc.h>
MOV R0,#10 ;TURN ON OSC #include<LCD_16x2_functions.c>
MOV A,#20H #include<reg51.h>
MOVX @R0,A
AGAIN: MOV R4,#80H ;READ void main(){
AND DISPLAY LCD_init();
ACALL LCD_COMMAND XBYTE[10]=0x20; //TURN ON OSC
MOV R0,#04 ;HOURS while(1){
MOVX A,@R0 LCD_command(0x80); //time
ACALL LCD_BCD LCD_BCD(XBYTE[4]); //SECONDS
MOV R4,#':' LCD_data(':');
ACALL LCD_DATA LCD_BCD(XBYTE[2]); //MINUTES
MOV R0,#02 ;MINUTES LCD_data(':');
MOV A,@R0 LCD_BCD(XBYTE[0]); //HOURS
ACALL LCD_BCD LCD_command(0xC0); //date
MOV R4,#':' LCD_BCD(XBYTE[7]); //DATE
ACALL LCD_DATA LCD_data('/');
MOV R0,#00 ;SECONDS LCD_BCD(XBYTE[8]); //MONTH
MOV A,@R0 LCD_data('/');
ACALL LCD_BCD LCD_data('2');

189
MOV R4,#0C0H LCD_data('0');
ACALL LCD_COMMAND LCD_BCD(XBYTE[9]); //YEAR
MOV R0,#07 ;DATE }
MOVX A,@R0 }
ACALL LCD_BCD
MOV R4,#'/'
ACALL LCD_DATA
MOV R0,#08 ;MONTH
MOV A,@R0
ACALL LCD_BCD
MOV R4,#'/'
ACALL LCD_DATA
MOV R4,#'2'
ACALL LCD_DATA
MOV R4,#'0'
ACALL LCD_DATA
MOV R0,#09 ;YEAR
MOV A,@R0
ACALL LCD_BCD
AJMP AGAIN
END

16.3WRITE A PROGRAM to set the time (12-hour mode) and date on RTC DS12887 in
binary format
Interfacing Diagram:

190
Assembly Embedded C

ORG 00H #include<reg51.h>


MOV R0,#10 ;ON OSC IN REG A #include<absacc.h>
MOV A,#20H
MOVX @R0,A void main(){
;BIN,12HRS IN REG B XBYTE[10]=0x20; //TURN ON OSC
MOV R0,#11 XBYTE[11]=0x85; //BIN,12HRS IN REG B
MOV A,#85H XBYTE[0]=00; //SET SECONDS
MOVX @R0,A XBYTE[2]=30; //SET MINUTES
MOV R0,#00 ;SET SECONDS XBYTE[4]=4; //SET HOURS
MOV A,#00 XBYTE[7]=12; //SET DATE
MOVX @R0,A XBYTE[8]=10; //SET MONTH
MOV R0,#02 ;SET MINUTES XBYTE[9]=17; //SET YEAR
MOV A,#30 XBYTE[11]=0x05; //B7=0 TO ALLOW
MOVX @R0,A //UPDATE
MOV R0,#4 ;SET HOURS }
MOV A,#04
MOVX @R0,A
MOV R0,#07 ;SET DAY
MOV A,#12
MOVX @R0,A
MOV R0,#08 ;SET MONTH
MOV A,#10
MOVX @R0,A
MOV R0,#09 ;SET YEAR
MOV A,#17
MOVX @R0,A
MOV R0,#03 ;B[7]=0 TO
ALLOW UPDATE
MOV A,#05H
MOVX @R0,A
END

191
16.4WRITE A PROGRAM to read the time (12-hour mode) and date from RTC DS12887
(binary format) and display on LCD
Interfacing Diagram:

Assembly Embedded C

ORG 00H #include<reg51.h>


ACALL LCD_INIT #include<absacc.h>
MOV R0,#10 ;TURN ON OSC #include<LCD_16x2_functions.c>
MOV A,#20H
MOVX @R0,A void main(){
AGAIN: MOV R4,#80H ;READ LCD_init();
AND DISPLAY XBYTE[10]=0x20; //TURN ON OSC
ACALL LCD_COMMAND while(1){
MOV R0,#04 ;HOURS LCD_command(0x80); // time
MOVX A,@R0 LCD_BIN2(XBYTE[4]);//SECONDS
ACALL LCD_BIN LCD_data(':');
MOV R4,#':' LCD_BIN2(XBYTE[2]); //MINUTES
ACALL LCD_DATA LCD_data(':');
MOV R0,#02 ;MINUTES LCD_BIN2(XBYTE[0]); //HOURS
MOV A,@R0 LCD_command(0xC0); //date
ACALL LCD_BIN LCD_BIN2(XBYTE[7]); /DATE
MOV R4,#':' LCD_data('/');
ACALL LCD_DATA LCD_BIN2(XBYTE[8]); //MONTH
MOV R0,#00 ;SECONDS LCD_data('/');
MOV A,@R0 LCD_data('2');
ACALL LCD_BIN LCD_data('0');

192
MOV R4,#0C0H LCD_BIN2(XBYTE[9]); //YEAR
ACALL LCD_COMMAND }
MOV R0,#07 ;DATE }
MOVX A,@R0
ACALL LCD_BIN
MOV R4,#'/'
ACALL LCD_DATA
MOV R0,#08 ;MONTH
MOV A,@R0
ACALL LCD_BIN
MOV R4,#'/'
ACALL LCD_DATA
MOV R4,#'2'
ACALL LCD_DATA
MOV R4,#'0'
ACALL LCD_DATA
MOV R0,#09 ;YEAR
MOV A,@R0
ACALL LCD_BIN
AJMP AGAIN
END

16.5WRITE A PROGRAM to generate a square wave with frequency 2 Hz on SQW pin of


RTC DS12887
Interfacing Diagram:

193
Assembly Embedded C

ORG 00H #include<reg51.h>


;TURN ON OSC and 2Hz SQW #include<absacc.h>
MOV R0,#10
MOV A,#2FH void main(){
MOVX @R0,A unsigned char val;
MOV R0,#11 XBYTE[10]=0x2F; //TURN ON OSC
;Enable SQW and 2Hz SQW
MOVX A,@R0 val=XBYTE[11]; //Enable SQW
SETB ACC.3 val=val||0x08;
MOVX @R0,A XBYTE[11]=val;
END }

16.6WRITE A PROGRAM to set alarm (exact time match) and corresponding interrupt on
IRQ pin of RTC DS12887 and make buzzer sound for few seconds at the time of
interrupt
Interfacing Diagram:

Assembly Embedded C

BUZZER EQU P0.2 #include<reg51.h>


ORG 00H ;reset location #include<absacc.h>
LJMP MAIN
ORG 03H ;external interrrupt 0 sbit BUZZER=P2^0;
LJMP ISR_EXT0 sbit EXT_EDGE=TCON^1;
void delay();
MAIN: void ISR_EXT0() interrupt 0{ //ISR external 0

194
MOV IE,#81H BUZZER=1;
SETB TCON.1 delay();
MOV R0,#10 ;TURN ON OSC }
MOV A,#20H
MOVX @R0,A void main(){
MOV R0,#11 ;BCD,24HRS IE=0x81; //enable external interrupt 0
MOV A,#0A3H EXT_EDGE=1; //and make it edge triggered
MOVX @R0,A XBYTE[10]=0x20; //TURN ON OSC
MOV R0,#00 ;SET SECONDS XBYTE[11]=0xA3; //BCD,24HRS
MOV A,#00H XBYTE[0]=0x00; //SET SECONDS
MOVX @R0,A XBYTE[2]=0x30; //SET MINUTES
MOV R0,#02 ;SET MINUTES XBYTE[4]=0x16; //SET HOURS
MOV A,#30H XBYTE[0]=0x10; //SET ALARM SECONDS
MOVX @R0,A XBYTE[2]=0x30; //SET ALARM MINUTES
MOV R0,#4 ;SET HOURS XBYTE[4]=0x16; //SET ALARM HOURS
MOV A,#16H XBYTE[11]=0x23; //B7=0 TO ALLOW
MOVX @R0,A //UPDATE
MOV R0,#07 ;SET DAY }
MOV A,#12H
MOVX @R0,A void delay(){
MOV R0,#08 ;SET MONTH unsigned int i;
MOV A,#10H for(i=0;i<40000;i++);
MOVX @R0,A }
MOV R0,#09 ;SET YEAR
MOV A,#17H
MOVX @R0,A
;SET ALARM
MOV R0,#01 ; SECONDS
MOV A,#10H
MOVX @R0,A
MOV R0,#03 ;MINUTES
MOV A,#30H
MOVX @R0,A
MOV R0,#5 ;HOURS
MOV A,#16H
MOVX @R0,A
;B7=0 TO ALLOW
UPDATE
MOV R0,#03
MOV A,#83H
MOVX @R0,A

ISR_EXT0: ;ISR external 0


SETB BUZZER

195
ACALL DELAY
ACALL DELAY
ACALL DELAY
CLR BUZZER
RETI

DELAY: ;Function for delay


MOV R0, #10 ;
LOOP2: MOV R1, #200 ;
LOOP1: MOV R2, #200 ;
LOOP: DJNZ R2, LOOP ;
DJNZ R1, LOOP1 ;
DJNZ R0, LOOP2 ;
RET
END

16.7WRITE A PROGRAM to generate alarm interrupt every half second on IRQ pin of RTC
DS12887 and make the LED blink
Interfacing Diagram:

196
Assembly Embedded C

ORG 00H ;reset location #include<reg51.h>

LJMP MAIN #include<absacc.h>

MAIN:

MOV R0,#10 ;TURN ON OSC void main(){

MOV A,#2FH XBYTE[10]=0x2F; //TURN ON OSC

MOVX @R0,A XBYTE[11]=0x43; //BCD,24HRS,2Hz

;BCD,24HRS,2Hz on IRQ pin //on IRQ pin

MOV R0,#11 }

MOV A,#43H

MOVX @R0,A

SJMP $

END

197

You might also like