0% found this document useful (0 votes)
61 views112 pages

FINAL MCI Lab Manual

Uploaded by

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

FINAL MCI Lab Manual

Uploaded by

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

DEPARTMENT OF COMPUTER AND COMMUNICATION ENGINEERING

LABORATORY MANUAL

U20CCP507 MICROCONTROLLER AND INTERFACING


LABORATORY (R2020)

1
MICROCONTROLLER AND L T P C Hours
U20CCP507 INTERFACING LABORATORY
0 0 2 1 30

LIST OF EXPERIMENTS

1. Basic programs to understand the Keil IDE for 8051

a. Assembling, compiling and simulating the code

b. Break points and step by step execution of the code

c. Calculating the delay for the given clock frequency

2. Developing an assembly program for accessing GPIO and Timer peripherals in 8051 boards

a. Blinking the LED by the defined rate in delay using timer

b. Using polling method read the status of switches

3. Developing an assembly program for invoking interrupt in 8051 target board

a. Control the LEDs by the external interrupts

b. handling multiple interrupts

c. handling timer interrupt

4. Developing C programs for accessing ADC through GPIO, timer peripherals and interrupts in 8051

5. Design a setup for a display system to display the data in 7 segment LED and LCD module

a. A number is incremented for the period of time and it should be shown in display

b. The stored alpha numeric string is displayed in LCD module

6. Design a setup for UART communication between 8051 target board and PC

a. The text stored in the 8051 program is send to PC

b. The text sent by PC is displayed in LCD module in 8051 target board

7. Basic sketch programs to understand the Arduino Galileo IDE

a. Developing the sketch program for blinking the LEDs

b. Using built in functions for accessing switch and LEDS

8. Design a system for an temperature monitoring application in Intel Galileo

9. Design a system for servo motor control application in Intel Galileo

10. Design a system for stepper motor control application along with ultra sonic sensor in Intel Galileo

11. Design a mini project either in 8051 target board or intel Galileo

2
Course Objectives
 To develop the code for basic concepts to understand Keil IDE for 8051.
 To experiment C code for accessing GPIO for interfacing switched and LEDs.
 To develop C code for accessing ADC through GPIO, timer peripherals and interrupts in 8051.
 To design analog sensors such as LDR, thermistor and temperature monitoring application in Intel
Galileo.
 To acquire the ability to design, implement servo motor and stepper motor application in Intel
Galileo.

CO No. Course Outcome

CO1 Describe and Implement 8051 instructions for solving mathematical problems (K3)
CO2 Use GPIO for interfacing switches and LEDs. (K3)

CO3 Use different methods for accessing timers peripheral and serial peripherals in 8051. (K3)

CO4 Design a system for temperature acquisition system in an intel Galileo board. (K3)

CO5 Analyze the memory requirements and delay for the system by implementing the
application in 8051 target board. (K3)

CO – PO Mapping

Program Course Outcome


Outcom CO 1 CO 2 CO 3 CO 4 CO5 Justification
e
PO 1 3 3 3 3 3 Students will be able to know the basic
concepts of microcontroller and
interfacing
PO 2 2 2 2 2 2 By learning this course alone students
cannot solve complex engineering
problems
PO 3 1 1 1 1 1 Simple problems can be solved by
understanding the basics of
Microcontroller
PO 4 1 1 1 1 1 Designing solutions for complex
engineering problems is not possible with
the basic knowledge of microcontroller

3
PO 5 2 2 2 2 2 Knowledge of modern tools is used to
solve complex engineering activities
PO 6 - - - - - No Relevance
PO 7 - - - - - No Relevance
PO 8 - - - - - No Relevance
PO 9 2 2 2 2 2 This course enables the leadership
quality and develops the quality to work
as team
PO 10 - - - - - No Relevance
PO 11 - - - - - No Relevance
PO 12 1 1 1 1 1 Basic knowledge of microcontroller alone
may not be able to provide lifelong
learning

4
Ex.No. 1.(a) STUDY OF 8051 MICROCONTROLLER Date:

AIM
To study the feature of 8051 microcontroller, architecture, pin details and special function registers
and Input and output ports

THEORY
 8051 is an 8-bit µc which comes under CISC processors and it uses Harvard architecture.
 8051 is available as a 40-pin chip which works at +5V.
 It has 8-bit data bus and 16-bit address bus.

THE 8051 MICROCONTROLLER ARCHITECTURAL FEATURES

 It has 8-bit CPU with registers A (the Accumulator) and B of 8-bit each.

 A register receives the result of all arithmetic operations. It is also used to hold
the data during external memory access.

5
 B register is mainly used to receive the extended result from multiply and divide
operations.
 It has 8-bit Program Status Word (PSW) register.

 The result of ALU operation is updated in PSW.

 It keeps track of overflow, carry, negative results etc.

 It also keeps track of which memory bank is currently selected.

 It has 16-bit program counter (PC) register.

 It is used to point to the next instruction to be fetched from code memory (ROM).

 Each time an instruction is fetched, PC is incremented so that it points to the


next instruction to be fetched for execution.
 PC is modified when a jump or call instruction is executed.

 It has 16-bit Data pointer (DPTR) register.

 It is used to access external data memory.

 It can be accessed individually as two 8-bit registers, DPH and DPL.

 It is under the control of the program.

 It has 8-bit Stack pointer (SP) register.

 It is used to point to the top of the stack.

 It grows in the direction of increasing memory address.

 It has Internal ROM or EPROM of 0 to 4K.

 It is the program memory which is read-only.

 8031 has 0K ROM

 8051 has 4K ROM

 8751 has 4K UV-EPROM

 It has Internal RAM of 128 bytes which is sectioned as follows:

 4 register banks, each containing 8 registers where each register size is 8-bit.
6
 16 bytes, which may be addressed at the bit level.

 80 bytes of general-purpose data memory.

 32 input/output pins arranged as four 8-bit ports: P0 - P3

 P0 is used as a general purpose I/O port. With presence of external memory


it functions as a multiplexed address (lower byte address A0-A7) and data bus (D0-
D7).
 P1 is used only as a general purpose I/O port.

 P2 is used as a general purpose I/O port. With presence of external memory


it functions as an address bus (higher byte address A8-A15).
 P3 is used as a general purpose I/O port. Alternate functions are
o interrupt inputs

o serial data I/O

o timer/counter input

o read/write control when external memory is used.

 Special Function Registers (SFRs) are dedicated RAM area (128 bytes) ranging
from 80H to FFH. SFRs contain control registers.
 Control registers: TCON, TMOD, SCON, PCON, IP, and IE.

 It has two 16-bit Timer/Counters: T0 and T1.

 It has one serial port for serial communication.

 SBUF is a serial port data buffer register which is used to hold the data to
be transmitted and receive the data via serial port.
 It has 2 external and 3 internal interrupt sources.

 It has Oscillator and clock circuits to generate timing signals for synchronization of all
operations in the microcontroller.

7
INTERNAL RAM ORGANIZATION
 The 128 bytes internal RAM is organized into three distinct area:

 32-bytes from address 00H to 1FH that make up 32 working registers organized
as four banks of eight registers each.
o Register banks are numbered 0-3

o 8 registers are named as R0-R7.

o Each register can be addressed by name or by its RAM address.

o Bits RS0 (bit 3) and RS1 (bit 4) in the PSW determine which bank of registers is
currently in use at any time program is running.
o Register banks not selected can be used as general-purpose RAM.

o Bank 0 is selected upon reset.

 A bit-addressable area of 16 bytes occupies RAM byte addresses 20H to 2FH,


forming a total of 128 addressable bits.
o An addressable bit may be specified by its bit address of 00H to 7FH, or 8
bits may form any byte address from 20H to 2FH.
 A general-purpose RAM area (Scratch pad memory) above the bit area, from 30H
to 7FH, are addressable as bytes.
FLAGS AND THE PROGRAM STATUS WORD (PSW)
 Flags are 1-bit registers provided to store the results of certain program instructions.

 There are instructions in 8051 which can check the flags status and make decisions

8
based on them.
 The 8051 has

 4 math flags which are updated based on result of math operations.

o Math flags include Carry (CY), Auxiliary Carry (AC), Overflow (OV), and
Parity (P).
 3 general-purpose user flags which may be used by the programmer to record
some event in the program.
o General-purpose User flags are named F0 (in PSW register), GF0 and
GF1 (in PCON register)

 The direct RAM address of PSW register is D0H.

 PSW register is bit addressable as PSW.0 to PSW.7

The PSW is shown in below figure:

Bit Symbol Function

7 CY Carry flag; CY=1 if carry is generated out of MSB or borrow is generated into
MSB. It is used in arithmetic, JUMP, ROTATE, and Boolean instructions

6 AC Auxiliary Carry flag; AC=1 if carry is generated from lower nibble to higher
nibble or borrow is generated from higher nibble to lower nibble. It is used for
BCD arithmetic.

5 F0 User Flag 0

4 RS1 Register bank Select bit 1

3 RS0 Register bank Select bit 0

RS1 and RS0 bits identify which of the four general-purpose register banks is currently in use by the
program.
RS1 RS0

9
0 0 Select register bank 0
0 1 Select register bank 1
1 0 Select register bank 2
1 1 Select register bank 3

2 OV Overflow flag; OV=1 if the result of operation exceeds the representable range
(- 128 to +127). It is used in arithmetic instructions

1 - Undefined; It is reserved for future use

0 P Parity flag; It shows the parity of register A. P=1 if register A contains odd
number of 1’s (odd parity).

SPECIAL FUNCTION REGISTERS (SFRs)


 SFRs may be addressed much like 128 byte internal RAM, using addresses from 80H
to FFH.
 Some SFRs are also bit-addressable. This feature allows the programmer to change
only what needs to be altered, leaving the remaining bits in that SFR unchanged.

 Not all of the addresses from 80H to FFH are used for SFRs, and attempting to use
an address that is not defined results in unpredictable results.
 SFRs are named in certain opcodes by their functional names, and are referenced by
other opcodes by their addresses.
 Note that PC is not part of SFR and has no internal RAM address.

 The SFR names and equivalent internal RAM addresses are given in the following table:
NAME FUNCTION INTERNAL RAM ADDRESS

A Accumulator 0E0H

B Arithmetic 0F0H

DPH Addressing external memory 83H

DPL Addressing external memory 82H

IE Interrupt enable control 0A8H

IP Interrupt priority 0B8H

P0 I/O port Latch 80H

P1 I/O port Latch 90H

P2 I/O port Latch 0A0H


10
P3 I/O port Latch 0B0H

PCON Power control 87H

PSW Program Status Word 0D0H

SCON Serial port control 98H

SBUF Serial port data buffer 99H

SP Stack Pointer 81H

TMOD Timer/Counter mode control 89H

TCON Timer/Counter control 88H

TL0 Timer 0 low byte 8AH

TH0 Timer 0 high byte 8CH

TL1 Timer 1 low byte 8BH

TH1 Timer 1 high byte 8DH

11
PIN- OUTS OF 8051 MICROCONTROLLER

 Out of 40 pins, 32 are I/O pins which are available as 4 parallel ports of 8-bits each.

 Port 0 (32-39):

o It is an 8-bit bi-directional I/O port.

o It is associated with a latch whose address is 80H.

o It is bit/byte addressable.

o During external memory access (RAM/ROM), it functions as multiplexed data

and lower-order address bus AD0-AD7.

 Port 1 (1-8):

o It is an 8-bit bi-directional I/O port.

o It is associated with a latch whose address is 90H.

12
o It is bit/byte addressable.

o It functions as simply an I/O port and it does not have any alternate functions.

 Port 2 (21-28):

o It is an 8-bit bi-directional I/O port.


o It is associated with a latch whose address is A0H.

o It is bit/byte addressable.

o During external memory access (RAM/ROM), it functions as higher-order


address bus A8-A15.
 Port 3 (10-17):

o It is an 8-bit bi-directional I/O port.

o It is associated with a latch whose address is B0H.

o It is bit/byte addressable.

o Each pin of this port has alternate functions:

 P3.0 (RxD): It is an input signal to serial port data buffer register SBUF,
through which microcontroller receives data of serial communication network.
 P3.1 (TxD): It is an output signal of serial port data buffer register SBUF,
through which microcontroller transmits data of serial communication
network.

 P3.2 ( INT 0 ) and P3.3 ( INT1): These are external interrupt input signals
through which microcontroller can be interrupted by peripheral.
 P3.4 (T0) and P3.5 (T1): These are input signals to internal timer-0 and
timer- 1 circuits respectively.

 P3.6 (WR ): It is an active low write output control signal. During external
RAM access, it is generated by microcontroller (WR = 0) to perform write
operation to external RAM.

 P3.7 ( RD ): It is an active low read output control signal. During external


RAM access, it is generated by microcontroller (RD = 0) to perform read

13
operation from external RAM.
 RST (9):

o It is an active high input signal used to reset microcontroller.

o To reset 8051 microcontroller, RST is made high for at least two machine cycles.

o Example: After reset, PC=0000H, SP = 07H, all internal RAM locations are
cleared to zero.
 XTAL2 (18) and XTAL1 (19):
o These two input lines for on-chip oscillator and clock generator circuit. A crystal
resonator is connected between these two pins.

 VCC (40):

It is connected to + 5V power supply.

 GND (20):

It is connected to ground reference.

 PSEN (29) – Program Store Enable:

o It is an active low output signal used to enable external program memory (ROM).

o It is connected to OE of external ROM.

o When PSEN = 0, ROM becomes enabled and microcontroller reads the


contents of external ROM locations.
 ALE (30) – Address Latch Enable:

o It is an active high output signal used to demultiplex AD0-AD7 of port0.

o When ALE goes high, external address latch becomes enabled and whatever is
there in input to latch will be available at the output of latch. When ALE goes
low, it is used as data bus.

 EA (31) – External Access:

o It is an active low input signal to the microcontroller.

o For 8051, this pin is connected to Vcc so that the microcontroller can access
both internal and external program memory (ROM). Internal ROM is selected for
14
address 0000H-0FFFH. Beyond this address (1000H-FFFFH) external ROM is
selected.
o For 8031, this pin is connected to GND so that the microcontroller can access
only external ROM.

ADDRESSING MODES

The different methods of specifying the location of the operand in an instruction is referred
to as addressing modes.

The different addressing modes supported in 8051 are:

 Immediate addressing mode

 Register addressing mode


 Direct addressing mode

 Register-indirect addressing mode

 Indexed addressing mode

Immediate addressing mode

 In this addressing mode, the operand value is specified as part of the instruction.

 The operand value is preceded by ‘#’ symbol to indicate immediate addressing mode
in the instruction.
 Only the source operand can be specified using this addressing mode.

 The destination operand can be either a register or a memory location.

 Examples:

MOV A,#34H

ANL A,#01000010B

ADD A,#20
MOV R2,#78H
MOV 26H,#10H
15
MOV @R0,#45H

Register addressing mode

 In this addressing mode, the operand value is specified in a register and the register
name is specified in the instruction.
 The registers that can be specified in this mode are A, R0-R7, DPTR. Other registers
can be specified using their direct RAM address.
 Either source operand or destination operand can be specified using this addressing
mode. Both the source and destination operands can be in this mode if one of the
operand is A register and other operand is register R0-R7
 Examples:

MOV A,#34H

ANL A,R0

ADD A,@R0

INC R0
MOV 26H,R3

Direct addressing mode (used to access internal data memory only)

 In this addressing mode, the address of the operand is specified as part of the instruction.

 The valid direct address that can be used is in the range 00H-7FH. The SFRs
implemented in the address range 80H-FFH can be referred using direct addressing
mode.
 Either source or destination or both the operands can be specified using this addressing
mode. The operand specified using this mode cannot be altered during execution of the
program.
 Examples:

MOV A,34H

ANL 20H,R0

ADD A,40H

16
MOV R2,01H

PUSH 0E0H

MOV 26H,35H

Register-Indirect addressing mode

 In this addressing mode, the address of the operand is specified in a register and
the register name is used in the instruction.
 The register name is preceded by ‘@’ symbol to indicate register-indirect
addressing mode in the instruction.
 The valid registers that can be used to hold the address are R0, R1, and DPTR.

 Either source or destination operand can be specified using this addressing mode.

 The operand specified using this mode can be altered during execution of the program.

 Examples:

MOV A,@R0 ADD A,@R0 MOV


@R1,01H MOVX A,@DPTR

Indexed addressing mode

 In this addressing mode, the effective address of the operand is calculated by adding
the offset held in A register with the base address held in DPTR or PC register.
 The expression A+DPTR or A+PC preceded by ‘@’ symbol is used to indicate indexed

addressing mode in the instruction.

 Only the source operand can be specified using this addressing mode.

 This addressing mode can also be used to access the look-up table entries stored in
the program memory.
 The operand specified using this mode can be altered during execution of the program.

 Example:

MOVC A,@A+DPTR

MOVC A,@A+PC
INSTRUCTION SET AT GLANCE
17
SL. INSTRUCTION LENGTH
DESCRIPTION CYCLE(S)
NO. MNEMONIC OPERAND(S) (BYTES)
ARITHMETIC OPERATIONS
1. ADD A,Rn Add register to Accumulator 1 1
2. ADD A,Direct Add direct byte to Accumulator 2 1
3. ADD A,@Ri Add indirect RAM to Accumulator 1 1
4. ADD A,#Data Add immediate data to Accumulator 2 1
5. ADDC A,Rn Add register to Accumulator with Carry flag 1 1
6. ADDC A,Direct Add direct byte to Accumulator with Carry flag 2 1
7. ADDC A,@Ri Add indirect RAM to Accumulator with Carry flag 1 1
8. ADDC A,#Data Add immediate data to Accumulator with Carry 2 1
flag
9. SUBB A,Rn Subtract register from Accumulator with Borrow 1 1
10. SUBB A,Direct Subtract direct byte from Accumulator with 2 1
Borrow
Subtract indirect RAM from Accumulator
11. SUBB A,@Ri 1 1
with Borrow
Subtract immediate data from Accumulator
12. SUBB A,#Data 2 1
with Borrow
13. INC A Increment Accumulator by one 1 1
14. INC Rn Increment register by one 1 1
15. INC Direct Increment direct byte by one 2 1
16. INC @Ri Increment indirect RAM by one 1 1
17. INC DPTR Increment Data pointer by one 1 2
18. DEC A Decrement Accumulator by one 1 1
19. DEC Rn Decrement register by one 1 1
20. DEC Direct Decrement direct byte by one 2 1

21. DEC @Ri Decrement indirect RAM by one 1 1


Multiply Accumulator and B. (A)=lower
22. MUL AB 1 4
byte, (B)=higher byte
Divide Accumulator by B.
23. DIV AB 1 4

18
(A)=Quotient, (B)=Remainder
24. DA A Decimal Adjust Accumulator 1 1
DATA TRANSFER OPERATIONS
25. MOV A,Rn Move register to Accumulator 1 1
26. MOV A,Direct Move direct byte to Accumulator 2 1
27. MOV A,@Ri Move indirect RAM to Accumulator 1 1
28. MOV A,#Data Move immediate data to Accumulator 2 1
29. MOV Rn,A Move Accumulator to register 1 1
30. MOV Rn,Direct Move direct byte to register 2 2
31. MOV Rn,#Data Move immediate data to register 2 1
32. MOV Direct,A Move Accumulator to direct byte 2 1
33. MOV Direct,Rn Move register to direct byte 2 2
34. MOV Direct,Direct Move direct byte to direct byte 3 2
35. MOV Direct,@Ri Move indirect RAM to direct byte 2 2
36. MOV Direct,#Data Move immediate data to direct byte 3 2
37. MOV @Ri,A Move Accumulator to indirect RAM 1 1
38. MOV @Ri,Direct Move direct byte to indirect RAM 2 2
39. MOV @Ri,#Data Move immediate data to indirect RAM 2 1
40. MOV DPTR,#Data16 Load Data pointer with a 16-bit constant 3 2
41. MOVC A,@A+DPTR Move code byte relative to DPTR to Accumulator 1 2
42. MOVC A,@A+PC Move code byte relative to PC to Accumulator 1 2
43. MOVX A,@Ri Move external RAM (8-bit address) to 1 2
Accumulator
Move external RAM (16-bit address) to
44. MOVX A,@DPTR 1 2
Accumulator

45. MOVX @Ri,A Move Accumulator to external RAM (8-bit 1 2


address)

Move Accumulator to external RAM (16-


46. MOVX @DPTR,A 1 2
bit address)

47. PUSH Direct Push direct byte onto stack 2 2


48. POP Direct Pop direct byte from stack 2 2
49. XCH A,Rn Exchange register with Accumulator 1 1
50. XCH A,Direct Exchange direct byte with Accumulator 2 1

19
51. XCH A,@Ri Exchange indirect RAM with Accumulator 1 1
Exchange low-order Digit indirect RAM with
52. XCHD A,@Ri 1 1
Accumulator
LOGICAL OPERATIONS
53. ANL A,Rn AND register to Accumulator 1 1
54. ANL A,Direct AND direct byte to Accumulator 2 1
55. ANL A,@Ri AND indirect RAM to Accumulator 1 1
56. ANL A,#Data AND immediate data to Accumulator 2 1
57. ANL Direct,A AND Accumulator to direct byte 2 1
58. ANL Direct,#Data AND immediate data to direct byte 3 2
59. ORL A,Rn OR register to Accumulator 1 1

60. ORL A,Direct OR direct byte to Accumulator 2 1


61. ORL A,@Ri OR indirect RAM to Accumulator 1 1
62. ORL A,#Data OR immediate data to Accumulator 2 1
63. ORL Direct,A OR Accumulator to direct byte 2 1
64. ORL Direct,#Data OR immediate data to direct byte 3 2
65. XRL A,Rn Exclusive-OR register to Accumulator 1 1
66. XRL A,Direct Exclusive -OR direct byte to Accumulator 2 1
67. XRL A,@Ri Exclusive-OR indirect RAM to Accumulator 1 1
68. XRL A,#Data Exclusive-OR immediate data to Accumulator 2 1
69. XRL Direct,A Exclusive-OR Accumulator to direct byte 2 1
70. XRL Direct,#Data Exclusive-OR immediate data to direct byte 3 2
71. CLR A Clear Accumulator 1 1
72. CPL A Complement Accumulator 1 1
73. RL A Rotate Accumulator Left 1 1
74. RLC A Rotate Accumulator Left through Carry flag 1 1
75. RR A Rotate Accumulator Right 1 1
76. RRC A Rotate Accumulator Right through Carry flag 1 1
77. SWAP A Swap nibbles within the Accumulator 1 1
BOOLEAN VARIABLE MANIPULATION
78. CLR C Clear Carry flag 1 1

20
79. CLR Bit Clear direct bit 2 1
80. SETB C Set Carry flag 1 1
81. SETB Bit Set direct bit 2 1
82. CPL C Complement Carry flag 1 1
83. CPL Bit Complement direct bit 2 1
84. ANL C,Bit AND direct bit to Carry flag 2 2
85. ANL C,/Bit AND complement of direct bit to Carry flag 2 2
86. ORL C,Bit OR direct bit to Carry flag 2 2
87. ORL C,/Bit OR complement of direct bit to Carry flag 2 2
88. MOV C,Bit Move direct bit to Carry flag 2 1
89. MOV Bit,C Move Carry flag to direct bit 2 2
PROGRAM AND MACHINE CONTROL
90. ACALL Addr11 Absolute Subroutine Call 2 2
91. LCALL Addr16 Long Subroutine Call 3 2
92. RET Return from Subroutine 1 2
93. RETI Return from Interrupt 1 2
94. AJMP Addr11 Absolute Jump 2 2
95. LJMP Addr16 Long Jump 3 2
96 SJMP Rel Short Jump (relative addr) 2 2
97. JMP @A+DPTR Jump indirect relative to the DPTR 1 2
98. JZ Rel Jump if Accumulator is zero 2 2
99. JNZ Rel Jump if Accumulator is Not zero 2 2
100. JC Rel Jump if Carry flag is set 2 2
101. JNC Rel Jump if Carry flag is Not set 2 2
102. JB Bit,Rel Jump if direct bit is set 3 2
103. JNB Bit,Rel Jump if direct bit id Not set 3 2
104. JBC Bit,Rel Jump if direct bit is set and Clear bit 3 2
105. CJNE A,Direct,Rel Compare direct to A and Jump if Not Equal 3 2
106. CJNE A,#Data,Rel Compare immediate to A and jump if Not Equal 3 2
Compare immediate to register and Jump if Not
107. CJNE Rn,#Data,Rel 3 2
Equal
Compare immediate to indirect and Jump if
108. CJNE @Ri,#Data,Rel 3 2
Not Equal

21
109. DJNZ Rn,Rel Decrement register and Jump if Not Zero 2 2
110. DJNZ Direct,Rel Decrement direct and Jump if Not Zero 3 2
111. NOP No Operation 1 1

Timer/Counter Programming

 The 8051 has two 16-bit timers: Timer0 and Timer1.

 These timers can be used either as timers to generate a time delay or as counters to
count events happening outside the microcontroller.
 Timer 0 can be accessed as two 8-bit registers, TL0 (Timer0 Low byte) and TH0
(Timer0 High byte) whose RAM addresses are 8AH and 8CH respectively.
 Timer 1 can be accessed as two 8-bit registers, TL1 (Timer1 Low byte) and TH1
(Timer1 High byte) whose RAM addresses are 8BH and 8DH respectively.
 Below figure shows Timer0 and Timer1 registers:

TMOD (Timer Mode) register (RAM address:89H)

 Both Timer0 and Timer1 use TMOD register to set the various timer operation modes.

 TMOD is an 8-bit register in which the lower 4 bits are set aside for Timer0 and the
upper 4 bits for Timer 1.

 M0 and M1 bits in both the nibbles are used to set the timer
mode. M1 M0 Mode Operating Mode
22
0 0 0 13-bit timer mode

0 1 1 16-bit timer mode

1 0 2 8-bit auto reload

1 1 3 Split timer mode

 C/T is used to decide whether the timer is used as a delay generator or an event
counter. If C/T = 0, then it is used as timer for delay generation (input from internal
system clock). The frequency for the timer is always 1/12th the frequency of the crystal
attached to 8051. If C/T = 1, then it is used as event counter to count each clock pulse
coming from external pin (Pin P3.4 for timer0 and P3.5 for timer1).
 If GATE = 0, then

 instructions TR0 = 1 and TR0 = 0 starts and stops the timer0,

 instructions TR1 = 1 and TR1 = 0 starts and stops the


timer1. (TR0 and TR1 are bits of TCON register)
If GATE = 1, then the timer is started and stopped by an external source (Pin P3.2 for
timer0 and P3.3 for timer1).

TCON register (RAM address: 88H)

 While TMOD controls the timer modes, another register called TCON controls the
timer/counter operations.

 Timer is started by setting TRx bit, which is called Timer Run control bit and it is
stopped by clearing TRx bit.
 Whenever a timer counts to its maximum value, it sets Timer overflow Flag, TFx.

Bit Symbol Function

TCON.7 TF1 Timer1 overflow Flag


23
Mode2 Programming:

The following are the characteristics and operations of mode2:

1. It is an 8-bit timer. Therefore, it allows only values of 00H to FFH to be loaded into the

timer’s register TH.

2. After TH is loaded with the 8-bit value, the 8051 gives a copy of it to TL. Then, the timer
must be started, which is done by the instruction TR0 = 1 for Timer0 and TR1=1 for
Timer1.
3. After the timer is started, it starts to count up by incrementing the TL register. It counts
up until it reaches its limit of FFH. When it rolls over from FFH to 00H, it sets high the
TF0 for Timer0 and TF1 for Timer1.
4. When TL register rolls from FFH to 0 and TF=1, TL is reloaded automatically with the
original value kept in TH register. To repeat the process, we must simply clear TF and
let it go without any need by the programmer to reload the original value. This makes
mode2 an auto-reload.
Steps to program in mode2:

To generate a time delay using the timer’s mode2, the following steps are taken:

1. Load the TMOD register with value indicating which timer (Timer0 or Timer1) is to be
used, and select timer mode as mode2.
2. Load the TH register with the initial count value.

3. Start the timer.

4. Keep monitoring the timer flag (TF) with the statement while(TF==0); to see whether it
is raised. Come out of the loop when TF goes high.
5. Clear the TF flag.

6. Go back to step4, since mode2 is auto-reload.

24
RESULT

Thus the feature of 8051 microcontroller, architecture, pin details and special function registers and
Input and output ports are studied.

Ex.No.1(b) STUDY OF KEIL C IDE WITH SIMPLE PROGRAMS Date:

AIM:

To perform basic programs to understand the Keil C IDE for 8051

APPARATUS REQUIRED

Keil C installed Personal computer

THEORY:

The Keil µVision IDE is a Windows-based software development platform that combines Project

Management, Source Code Editing, Program Debugging, and Flash Programming in a single,

powerful environment.

When you use the Keil µVision, the project development cycle is roughly the same as it is for

any other software development project.

1. Create a project, select the target chip from the device database, and configure the tool

25
settings.

2. Create source files in C or assembly.

3. Build your application with the project manager.

4. Correct errors in source files.

5. Test the linked application.

µVision5 has two operating modes:

 Build Mode: Allows you to translate all the application files and to generate executable

programs.

 Debug Mode: Provides you with a powerful debugger for testing your application.

In both operating modes you may use the source editor of µVision3 to modify your source code.

The Debug mode adds additional windows and stores an own screen layout.

To launch Keil µVision5 IDE goto Start menu and click on Keil µVision5

26
Next, Click on Project menu and select New µVision Project option as shown in below figure.

27
28
Now, create a new folder and go to that folder.

Give some valid Project file name and click on Save as shown in below figure.

29
Now select the target chip as Atmel from the device data base.

30
In Atmel, choose AT89C51 device and click on OK as shown in below figure.

31
You need not add the Standard 8051 Startup Code to Project Folder. So, click on No as shown
below.

32
Now, go to File menu and select New option to create a new file.

33
34
Now, edit your assembly language program.

Now, right click on Target1 in the Project Workspace and select Options for Target ‘Target1’
as shown in below figure.

35
Enter the Xtal frequency in the Target tab as shown in the figure below.

36
Go to Output tab and tick the option for Create HEX file.

37
Now, save your file with .asm extension as shown in below figure and see that the file is saved
in your folder.

38
Now, right click on Source Group1 in the Project Workspace and select Add Existing Files to Group
39
‘Source Group1’ as shown in below figure.

Now, browse your asm Source file in your folder and click on Add as shown below.

40
Once the file is added to the Source Group1, go to Project menu and click on Build target.

If there are no errors in your Source program then Build target is successful. If any errors,
then go to the source program and debug the errors and again Build target.

41
Now, go to Debug menu and click on Start/Stop Debug Session to start the debug session.

42
A dialog box appears indicating the code size limit in this open source IDE. Just click OK.

Now, you are in execution mode. You can view several windows in this mode such as
Memory Window to see the data in internal or external RAM memory, Disassembly window
to see the ROM address of each instruction and machine code generated for each
instruction etc.

43
Now, to execute your program step by step, go to Debug menu and click on Step option
as shown in below figure. For whole program execution, click on Run option in Debug
menu.

44
You can view the result of your program execution in appropriate window based on where you
are storing the result. i.e., either in register or in memory. To view the result in memory, give
i:00 (i stands for internal RAM) in the text box provided in the memory window as shown in
below figure. To view external RAM, give x:00 in the memory window. You can edit the
required memory locations.

45
If any window is not appearing then go to View menu and select required window in it. Below
figure shows the selection of Disassembly Window.The Disassembly Window shows the Code
memory with each instruction address, the machine code generated for each instruction and
also the instructions.

46
( c) In order to generate a delay of 1ms, the calculations using above steps are as follows.

1. NNNN = 1ms/1.085μs ≈ 922.

2. MMMM = 65536-922 = 64614.

3. 64614 in Hexadecimal = FC66h.

Load TH with 0xFC and TL with 0x66.


The interrupt programming for timers involves following steps :

1. Configure TMOD register to select timer(s) and its/their mode.

2. Load initial values in THx and TLx for mode 0 and 1; or in THx only for mode 2.

3. Enable Timer Interrupt by configuring bits of IE register.

4. Start timer by setting timer run bit TRx.

47
PROGRAMS:
BLOCK EXCHANGE OF DATA FROM ONE MEMORY LOCATION TO ANOTHER MEMORY LOCATION

ORG 00H
SJMP 30H
ORG 30H
MOV R0, #30H
MOV R1, #40H
MOV R2, #05H
LOOP: MOV A, @ R0
MOV B,A
MOV A, @ R1
MOV @ R0, A
MOV A, B
MOV @ R1,A
INC R0
INC R1
DJNZ R2, LOOP
HERE: SJMP HERE
END
Output:
Before Execution
R0 = 30H
R1 = 40H
R2 = 05H
Memory content:

30H: 01H
31H: 02H
32H: 03H
33H: 04H
34H: 05H
40H: A1H
41H: A2H

48
42H: A3H
43H: A4H
44H: A5H
After Execution
Each iteration swaps the content between memory locations pointed by R0 and R1. After 5 iterations:

30H ↔ 40H
31H ↔ 41H
32H ↔ 42H
33H ↔ 43H
34H ↔ 44H
Memory content:

30H: A1H
31H: A2H
32H: A3H
33H: A4H
34H: A5H
40H: 01H
41H: 02H
42H: 03H
43H: 04H
44H: 05H
Final Register Values
R0 = 35H (incremented 5 times)
R1 = 45H (incremented 5 times)
R2 = 00H (decremented to zero)

SUM OF SERIES OF OF N BYTES OF DATA


ORG 0000H
SJMP 30H
ORG 30H
MOV R0,#30H
MOV R1,#05H

49
MOV R3,#00H
MOV A,@R0
L1: INC R0
ADD A,@R0
MOV R2,A
JNC L2
INC R2
L2: DJNZ R1, L1
END
Sample Output
Before Execution
R0 = 30H
R1 = 05H
R2 = 00H
R3 = 00H
A = 10H (value at memory location 30H)

Memory content:
30H: 10H
31H: 20H
32H: 30H
33H: 40H
34H: 50H
After Execution:
R0 = 35H
R1 = 00H
R2 = F0H
R3 = 00H (unused)
A = F0H

ADDITION OF TWO 8 BIT NUMBERS


MOV DPTR,#8200
MOV Ro,#00
MOVX A,@DPTR
MOV R1,A
INC DPTR
MOVX A,@DPTR
ADD A,R1
JNC 810D
INC R0

50
INC DPTR
MOVX @DPTR,A
INC DPTR
MOV A,R0
MOVX @DPTR,A
HERE: SJMP HERE
Sample Input and Output
Before Execution
DPTR = 8200H
R0 = 00H
R1 = 00H
A = 00H
After Execution
Memory content:
8200H: 45H
8201H: 55H
8202H: 9AH
8203H: 00H

Register content:

DPTR = 8203H
R0 = 00H
R1 = 45H
SUBTRACTION OF TWO 8 BIT NUMBERS
MOV DPTR,#8200
MOV Ro,#00
MOVX A,@DPTR
MOV R1,A
INC DPTR
MOVX A,@DPTR
CLR C
SUBB A,R1
JNC 810E
INC R0
INC DPTR
MOVX @DPTR,A
INC DPTR
MOV A,R0
MOVX @DPTR,A
51
HERE: SJMP HERE

Sample Input & Output


Before Execution
DPTR = 8200H
R0 = 00H
R1 = 00H
A = 00H
External memory location 8200H: 55H
External memory location 8201H: 45H
After Execution
Memory content:
8200H: 55H
8201H: 45H
8202H: F0H
8203H: 01H

Register content:

DPTR = 8203H
R0 = 01H
R1 = 55H
A = 01H

MULTIPLICATION OF TWO 8 BIT NUMBERS


MOV DPTR,#8200
MOVX A,@DPTR
INC DPTR
MOV B,A
MUL AB
INC DPTR
MOVX @DPTR,A
MOV A,B
INC DPTR
MOVX @DPTR,A
HERE: SJMP HERE
Sample Input & Output
External memory location 8200H: 12H (18 in decimal)
External memory location 8201H: 34H (52 in decimal)
52
Before Execution
DPTR = 8200H
A = 00H
B = 00H

After Execution Memory content:


8200H: 12H
8201H: 34H
8202H: 44H
8203H: 01H
Register content:
DPTR = 8203H
A = 01H
B = 01H

DIVISION OF TWO 8 BIT NUMBERS

MOV DPTR,#8200
MOVX A,@DPTR
INC DPTR
MOV B,A
MOVX A,@DPTR
DIV AB
INC DPTR
MOVX @DPTR,A
MOV A,B
INC DPTR
MOVX @DPTR,A
HERE: SJMP HERE
Sample Input & Output
Memory content:

8200H: 30H
8201H: 06H
After Execution
Memory content:

8200H: 30H
8201H: 06H
8202H: 00H (quotient of 48/6)
8203H: 06H (remainder of 48/6)

53
RESULT:
Thus the basic programs assembling, compiling and simulating the code ,Break points and step by
step execution of the code in keil C is executed.

54
DEVELOPING THE 8051C PROGRAM FOR
Ex.No.2 Date:
BLINKING THE LED BY THE DEFINED RATE IN
DELAY USING TIMER

AIM:
To develop 8051C program for blinking the LED by the defined rate in delay using timer.

REQUIREMENT:

1.Keil C Software

PROGRAM:

// The delay function will generate a delay of 1mS.


#include<reg51.h>
#define ON 1
#define OFF 0
sbit led=P2^0;
unsigned int i=0;
void delay();
void delay()
{
TMOD = 0x01; // Timer0 mode1
TH0 = 0xFC; //initial value for 1ms
TL0 = 0x66;
TR0 = 1; // timer start
while(TF0==0); // check overflow condition
TR0 = 0; // Stop Timer
TF0 = 0; // Clear flag
}
void main()

55
{

while(1)
{
led = ON;
for(i=0;i<1000;i++)
{
delay();
}
led = OFF;
for(i=0;i<1000;i++)
{
delay();
}
}
}

The interrupt programming for timers involves following steps :

5. Configure TMOD register to select timer(s) and its/their mode.

6. Load initial values in THx and TLx for mode 0 and 1; or in THx only for mode 2.

7. Enable Timer Interrupt by configuring bits of IE register.

8. Start timer by setting timer run bit TRx.

In order to generate a delay of 1ms, the calculations using above steps are as follows.

4. NNNN = 1ms/1.085μs ≈ 922.

5. MMMM = 65536-922 = 64614.

6. 64614 in Hexadecimal = FC66h.

7. Load TH with 0xFC and TL with 0x66.

PROCEDURE

Step 1: Go to Keil µVision5 IDE and click on Project menu and select New µVision Project option.
Step 2: Create a new folder and give some valid Project file name and click on Save.

56
Step 3: Select the target chip as Atmel from the device data base and choose AT89C51 device.
Step 4: Create a new file and edit the assembly language program.

Step 5: Enter the Xtal frequency and go to Output tab and tick the option for Create HEX file.
Step 6: Browse the asm file and add it.
Step 7: Build the target. If there are no errors in your Source program then Build target is successful. If
any errors, then go to the source program and debug the errors and again Build target.
Step 8: Start the debug session. For executing the program, click on Run option in Debug
menu.
Step 9: After the execution, LED will be ON for 1 milli second and OFF for 1 milli second.

57
RESULT:

Thus the 8051 C program for blinking the LED by the defined rate in delay using timer is developed.

DEVELOPING THE 8051 C PROGRAM FOR


Ex.No.3a Date:
CONTROLLING THE LEDS BY HANDLING
MULTIPLE INTERRUPTS

AIM:
To develop 8051 C program for controlling the LEDs by handling multiple interrupts.

REQUIREMENT:

1.Keil C Software

Algorithm:
Initialization:

 Include the required header file for 8051 register definitions.


Define bit-addressable variables for LED control using sbit for led_timercontrol and led_externalcontrol,
both mapped to pin P1.0 and P1.1

 External Interrupt Service Routine (ISR):


Define a function external for handling the external interrupt:
Toggle the state of led_externalcontrol.
Timer Interrupt Service Routine (ISR):

 Define a function timer for handling the timer interrupt:


Toggle the state of led_timercontrol.
Main Function:

 Configure Timer 0:
 Set TMOD to 0x01 to select Timer 0 in mode 1 (16-bit timer mode).
 Load initial values TH0 and TL0 to 0x00.
 Enable interrupts:
 Set IE to 0x83 to enable external interrupt 0 (EX0), timer interrupt 0 (ET0), and global interrupt enable
(EA) bit.
 Start Timer 0 by setting TR0 to 1.
 Enter an infinite loop to keep the main function running and allow interrupts to occur.
 End of Main Function.

PROGRAM:
#include <reg51.h>

sbit led_timercontrol = P1^0; // Define led_timercontrol at P1.0


58
sbit led_externalcontrol = P1^1; // Define led_externalcontrol at P1.1 (different bit)

void external(void) interrupt 0 {


led_externalcontrol = ~led_externalcontrol; // Toggle led_externalcontrol
}

void timer(void) interrupt 1 {


led_timercontrol = ~led_timercontrol; // Toggle led_timercontrol
}

void main(void) {
TMOD = 0x01; // Set Timer 0 in mode 1 (16-bit timer mode)
TH0 = 0x00; // Initial high value for Timer 0
TL0 = 0x00; // Initial low value for Timer 0
IE = 0x83; // Enable EA (global interrupt), ET0 (timer 0 interrupt), EX0 (external interrupt 0)
TR0 = 1; // Start Timer 0

while (1); // Infinite loop to keep the program running


}
PROCEDURE

Step 1: Go to Keil µVision5 IDE and click on Project menu and select New µVision Project option.
Step 2: Create a new folder and give some valid Project file name and click on Save.
Step 3: Select the target chip as Atmel from the device data base and choose AT89C51 device.
Step 4: Create a new file and edit the assembly language program.
Step 5: Enter the Xtal frequency and go to Output tab and tick the option for Create HEX file.
Step 6: Browse the .C file and add it.
Step 7: Build the target. If there are no errors in your Source program then Build target is successful. If
any errors, then go to the source program and debug the errors and again Build target.
Step 8: Start the debug session. For executing the program, click on Run option in Debug
menu.

RESULT:

Thus the 8051 C program is executed for controlling the LEDs by handling multiple interrupts.

59
DEVELOPING THE 8051C PROGRAM FOR
Ex.No.3b Date:
CONTROLLING THE LEDS BY HANDLING
TIMER INTERRUPTS

AIM:
To develop an assembly program for controlling the LEDs by handling timer interrupts.
REQUIREMENT:

1.Keil C Software

Algorithm for Blinking LED with Timer Interrupt Method

1. Initialize Timer and Port


o Set the Timer 0 mode to mode 1 (TMOD = 0x01;).
o Set the initial values for Timer 0 (TH0 and TL0) to achieve a delay of approximately 1 second.
o Configure Port 1 for output (assuming LED is connected to Port 1).

2. Main Program Loop (main function)


o Enable Timer 0 (TR0 = 1;) to start counting.
o Enter an infinite loop (while (1)) for continuous operation.

3. LED Control and Delay


o Inside the loop:
 Set Port 1 (P1) to output 01010101 (binary 0x55).
 Call the Delay() function to create a delay.
 Set Port 1 to output 10101010 (binary 0xAA).
 Call the Delay() function again for the same delay.

4. Delay Function (Delay)


o Configure Timer 0 (TH0 and TL0) with appropriate values for the desired delay.
o Start Timer 0 (TR0 = 1;) to begin counting.
o Wait until Timer 0 flag (TF0) is set, indicating that the delay has completed.
Stop Timer 0 (TR0 = 0;), clear Timer 0 flag (TF0 = 0;), and prepare Timer 0 for the next delay.
PROGRAM:
// Use of Timer mode0 for blinking LED with a delay of I second using Timer interrupt method
// XTAL frequency 11.0592MHz
#include <reg51.h>
void Delay(void); // Function declaration
void main(void)
{
TMOD = 0x01; // Timer 0 mode 1 (16-bit timer mode)
TH0 = 0x4C; // Initial value for 1-second delay (adjust based on XTAL frequency)
TL0 = 0x00;
TR0 = 1; // Start Timer 0

while (1)
{
P1 = 0x55; // Output 01010101 to Port 1
Delay(); // Function calling
60
P1 = 0xAA; // Output 10101010 to Port 1
Delay(); // Function calling
}
}

void Delay()
{
while (TF0 == 0); // Wait until Timer 0 flag TF0 is set
TR0 = 0; // Stop Timer 0
TF0 = 0; // Clear Timer 0 flag
TH0 = 0x4C; // Reload Timer 0 high byte for next delay
TL0 = 0x00; // Reload Timer 0 low byte for next delay
TR0 = 1; // Restart Timer 0
}

The interrupt programming for timers involves following steps :


1. Configure TMOD register to select timer(s) and its/their mode.
2. Load initial values in THx and TLx for mode 0 and 1; or in THx only for mode 2.
3. Enable Timer Interrupt by configuring bits of IE register.
4. Start timer by setting timer run bit TRx.
In order to generate a delay of 1ms, the calculations using above steps are as follows.
NNNN = 1ms/1.085μs ≈ 922.
19200 in Hexadecimal = 4C00h.
Load TH with 0x4C and TL with 0x00
The delay can be approximated using the formula: Delay=(65536−(TH0×256+TL0))/(System Clock Frequency)
Here, TH0 = 0x4C and TL0 = 0x00, so the initial count (TH0 * 256 + TL0) is 0x4C00.

For an 11.0592 MHz clock, the actual delay in seconds would be:
Delay (seconds)=(65536−19200)/11.0592×106≈1 second

Detailed Calculation:
Initial Timer Value (TH0 and TL0):
TH0 = 0x4C and TL0 = 0x00,The initial count value (TH0 * 256 + TL0) is 0x4C00.
In decimal, this is 19200.
PROCEDURE
Step 1: Go to Keil µVision5 IDE and click on Project menu and select New µVision Project option.
Step 2: Create a new folder and give some valid Project file name and click on Save.
Step 3: Select the target chip as Atmel from the device data base and choose AT89C51 device.
Step 4: Create a new file and edit the assembly language program.
Step 5: Enter the Xtal frequency and go to Output tab and tick the option for Create HEX file.
Step 6: Browse the .C file and add it.
Step 7: Build the target. If there are no errors in your Source program then Build target is successful. If
any errors, then go to the source program and debug the errors and again Build target.
Step 8: Start the debug session. For executing the program, click on Run option in Debug menu.
Open the "Peripherals" window or "I/O Ports" to monitor the state of Port 1 (P1).
As the program runs, you should see the LED connected to Port 1 blinking with a delay of approximately 1 second
between toggles. The pattern of blinking will alternate between 01010101 and 10101010 on Port 1.

61
RESULT:

Thus the 8051 C program for controlling the LEDs by handling timer interrupts.

Ex.No.4 Develop C program for interfacing ADC with 8051 Date:

AIM:

To develop C program for interfacing ADC with 8051


REQUIREMENT:

1. Keil C Software
2. Proteus Software

THEORY:
ADC0804 chip
The ADC0804 IC is an 8-bit parallel ADC in the family of the ADC0800 series from National
Semiconductor (www.national.com). It is also available from many other manufacturers. It works with +5 V
and has a resolution of 8 bits. In the ADC0804, the conversion time varies depending on the clocking
signals applied to the CLK IN pin, but it cannot be faster than 110 μs. The following is the ADC0804 pin
description.
CS
Chip select is an active-low input used to activate the ADC0804 chip. To access the ADC0804,
this pin must be low.
RD (read)
This is an input signal and is active low. The ADC converts the analog input to its binary equivalent
and holds it in an internal register. RD is used to get the converted data out of the ADC0804 chip. When
CS = 0, if a highto-low pulse is applied to the RD pin, the 8-bit digital output shows up at the D0–D7 data
pins. The RD pin is also referred to as output enable (OE).
WR (write; a better name might be “start conversion”)
This is an active-low input used to inform the ADC0804 to start the conversion process. If CS = 0
when WR makes a low-to-high transition, the ADC0804 starts converting the analog input value of Vin to
an 8-bit digital number. The amount of time it takes to convert varies depending on the CLK IN and CLK R
values explained below. When the data conversion is complete, the INTR pin is forced low by the
ADC0804.
CLK IN and CLK R
CLK IN is an input pin connected to an external clock source when an external clock is used for
timing. However, the 804 has an internal clock generator. To use the internal clock generator (also called
self-clocking) of the ADC0804, the CLK IN and CLK R pins are connected to a capacitor and a resistor, as
shown in Figure 1. In that case, the clock frequency is determined by the equation:

62
f = 1/1.1 RC

Typical values are R = 10K ohms and C = 150 pF. Substituting in the above equation, we get f =
606 kHz. In that case, the conversion time is 110 μs.

INTR (interrupt; a better name might be “end of conversion”)

This is an output pin and is active low. It is a normally high pin and when the conversion is
finished, it goes low to signal the CPU that the converted data is ready to be picked up. After INTR goes
low, we make CS = 0 and send a high-to-low pulse to the RD pin to get the data out of the ADC0804 chip.

Vin (+) and Vin (−)

These are the differential analog inputs where Vin = Vin (+) − Vin (−). Often the Vin (−) pin is
connected to ground and the Vin (+) pin is used as the analog input to be converted to digital.

VCC

This is the +5 V power supply. It is also used as a reference voltage when the Vref/2 input (pin 9)
is open (not connected).

Vref /2
Pin 9 is an input voltage used for the reference voltage. If this pin is open (not connected), the
analog input voltage for the ADC0804 is in the range of 0 to 5 V (the same as the Vcc pin). However, there
are many applications where the analog input applied to Vin needs to be other than the 0 to +5 V range.
Vref /2 is used to implement analog input voltages other than 0 to 5 V. For example, if the analog input
range needs to be
0 to 4 V, Vref/2 is connected to 2 V. Table 2 shows the Vin range for various Vref/2 inputs.

D0–D7
63
D0–D7 (D7 is the MSB) are the digital data output pins since ADC0804 is a parallel ADC chip.
These are tri-state buffered and the converted data is accessed only when CS = 0 and RD is forced low.
To calculate the output voltage, use the following formula

Dout = Vi / step size

where Dout = digital data output (in decimal), Vin = analog input voltage, and step size (resolution) is the
smallest change, which is (2 × Vref/2)/256 for ADC0804.

Procedure
1. Setting Up the Development Environment

 Install Keil µVision IDE:


o Download and install Keil µVision IDE from the official website (www.keil.com).
o Ensure you have the necessary compiler and debugger for the 8051 microcontroller.

 Install Proteus Simulation Software:


o Download and install Proteus simulation software from the official website (www.labcenter.com).
o Make sure to install the version that supports the 8051 microcontroller and relevant peripherals like ADC.

2. Creating the C Program in Keil µVision

 Open Keil µVision:


o Create a new project (File > New Project) and select the 8051 microcontroller model you are using (e.g.,
AT89C51, AT89S52).

 Write the ADC Interface Program:


o Write the C program to interface with the ADC. This involves initializing the ADC, reading analog inputs,
converting them to digital, and processing/displaying the results as needed.

 Compile the Program:


o Build (Project > Build Target) and compile your program in Keil µVision to check for errors and generate the
hex file (*.hex).

3. Integrating with Proteus Simulation

 Open Proteus:
o Launch Proteus simulation software.

 Create a New Project in Proteus:


o Create a new project (File > New Project) or open an existing project.

 Add 8051 Microcontroller:


o Drag and drop the 8051 microcontroller component (P89V51RD2, AT89C51, etc.) onto the workspace.

 Configure ADC Component:


o Add the ADC component compatible with your microcontroller model (e.g., ADC0804, ADC0808).
o Connect the ADC component to the appropriate microcontroller pins (input/output lines).

 Add Other Components (Optional):

64
o Include other components as required by your project, such as LEDs, resistors, capacitors, and power
sources.

 Load Hex File:


o Load the *.hex file generated by Keil µVision into the 8051 microcontroller in Proteus (Program File option in
microcontroller properties).

4. Setting Up Simulation Parameters

 Define Analog Input (if Simulating):


o Define analog input signals to the ADC in Proteus simulation settings. This simulates real-world analog
signals that the ADC will convert.

 Run the Simulation:


o Start the simulation in Proteus to execute your program.
o Monitor the behavior of the ADC interfacing logic, including digital outputs and any displayed results (e.g.,
LEDs).

5. Debug and Verify


 Debugging in Proteus:
o Use Proteus simulation debugging features to trace execution, inspect variables, and analyze ADC
readings.
o Verify that the ADC interfacing program behaves as expected under different conditions.

6. Iterate and Optimize


 Iterate Based on Simulation Results:
o Modify your C program in Keil µVision based on simulation results and optimizations needed.
o Re-compile, generate a new *.hex file, and reload it into Proteus for further testing.

7. Final Testing and Validation


 Physical Hardware Testing:
o Once satisfied with simulation results, implement and test the program on physical hardware with actual
ADC and 8051 microcontroller setups.
o Verify functionality and make any final adjustments as necessary.

CIRCUIT DIAGRAM:

65
Algorithm for ADC Interface Program

 Initialize Pin Definitions:


o Define input as Port 3 (P3), assuming it reads ADC values.
o Define output as Port 0 (P0), assumed to be connected to LEDs.

 Main Function:
o Set P3 as input (input = 0xFF).
o Set P0 as output (output = 0x00).

 Infinite Loop Execution:


o Continuously execute the following steps:
o Call the adc() function to read ADC values and update LED display.

 ADC Function (adc()):


o Set rd (Read pin) to 1 and wr (Write pin) to 0 to prepare for ADC read operation.
o Delay for a predetermined time (delay(10)) to ensure proper timing for ADC operation.
o Set wr back to 1 to initiate ADC conversion.
o Wait in a loop until intr (Interrupt pin, assumed to be P1^2) is 0, indicating ADC conversion completion.
o Set rd to 0 to end ADC read operation.
o Read ADC value from input (assumed to be ADC result) and store it in output (connected to LEDs via P0).
o Delay for another period (delay(10)) before possibly clearing an interrupt flag (intr = 1).

 Delay Function (delay(unsigned int t)):


o Accepts an integer t as input.
o Executes nested loops (for loops) to create a delay based on t.
o Provides timing control for operations like ADC conversion and LED updates.

PROGRAM:
#include <reg51.h>
#define input P3 // Input port (read values of ADC)
#define output P0 // Output port (connected to LEDs)
void delay(unsigned int t);
void adc();
sbit wr = P1^1; // Write pin
sbit rd = P1^0; // Read pin
sbit intr = P1^2; // Interrupt pin
void main() {
input = 0xFF; // Declare port P3 as an input port
output = 0x00; // Declare port P0 as an output port
while (1) {
adc();
} }
void delay(unsigned int t) {
unsigned int i, j;
for (i = 0; i < t; i++) {
for (j = 0; j < 1275; j++) {
// Delay loop
} } }
void adc() {
rd = 1;
wr = 0;
delay(10);
wr = 1;
while (intr == 1); // Wait for interrupt (assuming this checks the interrupt pin correctly)
66
Ex.No.5 DESIGN A SETUP FOR A DISPLAY SYSTEM TO Date:
rd = 0;
DISPLAY THE DATA IN 7 SEGMENT LED AND LCD output
= input; MODULE //
Output ADC
value to LEDs (assuming P0 is connected to LEDs)
delay(10);
intr = 1; // Clear interrupt flag (assuming this is the correct way to handle interrupts)
}
PROCEDURE:
Step 1: Go to Keil µVision5 IDE and click on Project menu and select New µVision Project option.
Step 2: Create a new folder and give some valid Project file name and click on Save.
Step 3: Select the target chip as Atmel from the device data base and choose AT89C51 device.
Step 4: Create a new file and edit the assembly language program.
Step 5: Enter the Xtal frequency and go to Output tab and tick the option for Create HEX file.
Step 6: Open the Proteus Software build the circuit using Circuit diagram

Step 7: Set the oscillator frequency as 11.0592MHz

Step 8: Link the Microcontroller through browse option to proper file location and run the file in proteus software

RESULT:

Thus ADC s interfaced with 8051using C program and output is executed using Proteus Software.

AIM:
To design a setup for a display system to display the data in
a. 7 segment LED
b. LCD module.
APPARATUS REQUIRED:
 Personal computer with Proteus software installed.
THEORY:
a. 7-Segment Display interfacing circuit

Description:
A Seven segment display is the most basic electronic display. It consists of eight LEDs which are
associated in a sequence manner so as to display digits from 0 to 9 when proper combinations of
LEDs are switched on. A 7-segment display uses seven LEDs to display digits from 0 to 9 and the
8th LED is used for dot. A typical seven segment looks likes as shown in figure below.

67
The 7-segment displays are used in a number of systems to display the numeric information. They can
display one digit at a time. Thus the number of segments used depends on the number of digits to display.
Here the digits 0 to 9 are displayed continuously at a predefined time delay.

The 7-segment displays are available in two configurations which are common anode and common cathode.
Here common anode configuration(7SEG- MPX1-CA) is used because output current of the microcontroller
is not sufficient enough to drive the LEDs. The 7-segment display works on negative logic, we have to
provide logic 0 to the corresponding pin to make on LED glow.

The following table shows the hex values used to display the different digits.

68
Algorithm for Display System with 7-Segment LED and LCD Module
Initialization
1. Initialize Pins and Variables:
o Define a as a control signal for the display (e.g., enable or data line).
o Define an array n[] with segment patterns for the 7-segment display.
o Declare loop control variables i and j.
Main Function
2. Main Loop (while(1)):
o Enter an infinite loop to continuously update the display.

3. 7-Segment Display Update:


o Enable the display (a = 1;).

4. Display Loop (for(i=0; i<10; i++)):


o Iterate through the n[] array to cycle through different segment patterns.
o Set P2 (connected to the 7-segment display) to n[i] to display the current segment pattern.

5. Delay for Timing:


o Implement a delay (for(j=0; j<60000; j++);) to control the display refresh rate. Adjust the
delay value based on desired timing.

6. LCD Module Integration (Example):


o Integrate LCD module functionalities if available:
 Initialize the LCD module and necessary pins.
 Write data to the LCD using specific functions (lcd_write, etc.).

7. Additional Logic:
o Add any additional logic or operations required for both displays.
o Handle interruptions or errors that may occur during operation.

69
CIRCUIT DIAGRAM

Program:
#include <reg51.h>
sbit a = P3^0;
void main() {
unsigned char n[10] = {0x40, 0xF9, 0x24, 0x30, 0x19, 0x12, 0x02, 0xF8, 0xE0, 0x10};
unsigned int i, j;
a = 1; // Set P3.0 high
while(1) {
for(i = 0; i < 10; i++) {
P2 = n[i];

for(j = 0; j < 60000; j++); // Delay loop

} } }

b. LCD Module

LCD stands for liquid crystal display which can display the characters per line. Here 16 by 2 LCD
display can display 16 characters per line and there are 2 lines. In this LCD each character is
displayed in 5*7 pixel matrix.

70
LCD Display

LCD is very important device which is used for almost all automated devices such as washing machines,
an autonomous robot, power control systems and other devices. This is achieved by displaying their
status on small display modules like 7-seven segment displays, multi segment LEDs etc. The reasons
being, LCDs are reasonably priced, easily programmable and they have a no limitations of displaying
special characters.

It consists of two registers such as command/instruction register and data register.

The command/instruction register stores the command instructions given to the LCD. A command is an
instruction which is given to the LCD that perform a set of predefined tasks like initializing, clearing the
screen, setting the cursor posing, controlling display etc.

The data register stores the data to be displayed on LCD. The data is an ASCII value of the characters
to be displayed on the LCD.

Operation of LCD is controlled by two commands. When RS=0, R/W=1 it reads the data and when
RS=1, R/W=0, it writes (print) the data.
LCD uses following command codes:

71
CIRCUIT DIAGRAM

Algorithm

1. Initialization:
o Set P2 to 0x00 to clear port 2.

2. Main Loop:
o Enter an infinite loop.
o Initialize the LCD with the following commands:

 Send 0x38 (Function set: 8-bit mode, 2 lines, 5x7 dots).


 Delay.
72
 Send 0x0E (Display ON, cursor ON).
 Delay.
 Send 0x01 (Clear display).
 Delay.
 Send 0x06 (Entry mode set: increment cursor).
 Delay.
 Send 0x86 (Set cursor position to 6th position on the first line).
 Delay.
o Display the characters "CCE":
 Send data 'C'.
 Delay.
 Send data 'C'.
 Delay.
 Send data 'E'.
 Delay.
3. LCD Command Function (lcdcmd):

o Set P2 to the command value.


o Set rs = 0, rw = 0, and en = 1.
o Short delay.
o Set en = 0.

4. LCD Data Function (lcddata):


o Set P2 to the data value.
o Set rs = 1, rw = 0, and en = 1.
o Short delay.
o Set en = 0.

5. Delay Function (MSDelay):


o Use nested loops to create a delay based on the provided delay parameter.

Program:

#include <reg51.h>
sbit rs = P1^0; // Register select pin
sbit rw = P1^1; // Read/Write pin
sbit en = P1^2; // Enable pin

void lcddata(unsigned char);


void lcdcmd(unsigned char);
void MSDelay(unsigned int);

void main() {
P2 = 0x00; // Clear port 2
while (1) {
lcdcmd(0x38); // Function set: 8-bit mode, 2 lines, 5x7 dots

73
MSDelay(50); // Delay for command to process
lcdcmd(0x0E); // Display ON, cursor ON
MSDelay(50); // Delay for command to process
lcdcmd(0x01); // Clear display
MSDelay(50); // Delay for command to process
lcdcmd(0x06); // Entry mode set: increment cursor
MSDelay(50); // Delay for command to process
lcdcmd(0x86); // Set cursor position to 6th position on the first line
MSDelay(50); // Delay for command to process

lcddata('C'); // Display 'C'


MSDelay(50); // Delay for data to process
lcddata('C'); // Display 'C'
MSDelay(50); // Delay for data to process
lcddata('E'); // Display 'E'
MSDelay(50); // Delay for data to process
}
}

void lcdcmd(unsigned char value) {


P2 = value; // Send command to port 2
rs = 0; // Command mode
rw = 0; // Write mode
en = 1; // Enable high
MSDelay(1); // Short delay
en = 0; // Enable low
}

void lcddata(unsigned char value) {


P2 = value; // Send data to port 2
rs = 1; // Data mode
rw = 0; // Write mode
en = 1; // Enable high
MSDelay(1); // Short delay
en = 0; // Enable low
}

74
void MSDelay(unsigned int delay) {
unsigned int i, j;
for (i = 0; i < delay; i++)
for (j = 0; j < 120; j++); // Calibrated delay loop
}

The program initializes the LCD, then continuously displays "CCE" with appropriate delays between each
command and data write operation.

RESULT:
Thus a setup for a display system to display the data in 7 segment LED and LCD module is designed
and executed using proteus software.

75
DESIGN A SETUP FOR UART
Ex.No.6 Date:
COMMUNICATION BETWEEN PIC 16F877A
AND PC

AIM:
To establish a serial communication link between the PC and the PIC 16F877A
APPARATUS REQUIRED
1. PIC Trainer Kit.
2. Power chord
3. RS232 Cable.
SOFTWARE USED
1.PIC C Compiler
2. PIC ISP
3. Hyper terminal
THEORY
Serial communication is used either to control or to receive data from an embedded microprocessor.
Serial communication is a form of communication in which the bits is begin transferred from one after the
oather in a timed sequence on a single wire. Serial communication has become the standard for inter
computer communication.
RS232C:
Fig 1.1 show the waveform on a single conductor to transmit a byte (0x41) serially. The output waveform of
PIC16F877A is in TTL-level. The voltage levels of the RS232C are used to assure error-free transmission
over greater distances than would be possible with TTL levels. So TTL level waveform is usually converted
to RS232 level wave form shown in Fig 1.1.

Fig 1.1 Serial Waveforms

76
Serial Port:
PIC 16F877A provides a transmit channel and a receive channel of serial communication. The transmit data
pin (TXD) is specified at P3.1, and the receive data pin (RXD) is at P3.0. Since the voltage levels of the
RS232C are used to assure error free transmission over greater distances then would be possible.

All modes are controlled through SCON, the Serial Control register. The SCON bits are defined as SM0,
SM1, SM2, REN, TB8, RB8, TI, RI from MSB to LSB. The timers are controlled using TMOD (the Timer
mode register) and TCON (Timer Control register).

CONNECTION DIAGRAM

RS232 / Serial Port

C
PIC P
16F877A U

RS232 / Serial Port

9V Power Supply
Fig 1. Connection diagram for Serial communication between PC and PIC Microcontroller

PROCEDURE
1. Connect the 9V Adaptor with power supply of the PIC Development board.
2. Connect the MAX/RS232 cable between PIC Development board and PC.
3. Write the program in PIC C IDE compiler.
4. Compile the program and create the HEX file.
5. Download the HEX file to PIC Development board using PIC ISP software
6. After HEX file is downloaded to the kit, set the PSEN Pin to high position, reset the PIC Development
board.
7. Set the Baud rate as 9600 and Com1 for connection (at PC), reset the PIC Development board.
8. Check the string which will be displayed in the serial window.

77
Algorithm:

1. Start
2. Include header file:
o #include <pic16f877.h>
3. Set clock frequency:
o #use delay(clock=20000000)
4. Configure RS232:
o #use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)
5. Main Function:
o Begin Infinite Loop:
1. Print the string "Microcontroller and Interfacing Laboratory" with newline and carriage
return:
 printf("Microcontroller and Interfacing Laboratory\n\r");
2. Delay for 1 second:
 delay_ms(1000);
o End Infinite Loop

PROGRAM:
#include <pic16f877.h>
#use delay(clock=20000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)

void main(void) {
while (1) {
printf("Microcontroller and Interfacing Laboratory\n\r");
delay_ms(1000); // Adding a delay to prevent overwhelming the serial buffer
}
}

The output of the program will be a continuous stream of the text "Microcontroller and Interfacing
Laboratory" sent over the serial port at a baud rate of 9600.

RESULT
78
Thus the serial communication link between the PC and the PIC 16F877A is established and the
string from PIC to PC (“Microcontroller and Interfacing Laboratory") is transferred.

79
DEVELOPING THE SKETCH PROGRAM FOR
Ex.No.7a Date:
BLINKING THE LEDS USING ARDUINO

AIM:

To develop the sketch program for blinking the LEDs, by using Arduino Development Board.

REQUIREMENT:

1. Arduino Board

2. Arduino IDE 1.05

3. Hook up wire

4. LED

5. Resistor

6. Bread Board

CONNECTION DIAGRAM:

Connection Diagram for Blinking the LED

80
Short Algorithm:

1. Start
2. Define ledPin: int ledPin = 8;
3. Setup Function:
o Configure pin 8 as output.
4. Main Loop:
o Begin Infinite Loop:
 Set pin 8 HIGH (LED ON).
 Delay for 1 second.
 Set pin 8 LOW (LED OFF).
 Delay for 1 second.
o End Infinite Loop
5. End

PROGRAM:
int ledPin = 8; // definition of digital pin 8 as pin to control the LED
void setup() {
pinMode(ledPin, OUTPUT); // Set the digital pin 8 mode to OUTPUT
}
void loop() {
digitalWrite(ledPin, HIGH); // Set pin 8 to HIGH (5V)
delay(1000); // Wait for 1 second
digitalWrite(ledPin, LOW); // Set pin 8 to LOW (0V)
delay(1000); // Wait for 1 second
}

PROCEDURE
Step 1: Make the connection with necessary components as per the pin configuration.
Step 2: Click the open-source Arduino Software (IDE) and write the code.
Step 3: The connection is given as per the connection diagram.
Step 4: Upload the sketch to the Arduino Uno board.
Step 5: Click the Upload icon to upload the code to the Arduino board.
Step 6: If "Done uploading" appears at the bottom of the window, it means the sketch has
been successfully uploaded.
Step 7: LED automatically made ON and OFF with the specified delay in the program.

RESULT:

81
Thus the program for blinking the LEDs, by using Arduino Development Board is developed.

DEVELOPING THE SKETCH PROGRAM FOR


Ex.No.7b Date:
CONTROLLING LED WITH SWITCH BUTTON

AIM:
To develop a basic sketch program using built in functions of Arduino uno for controlling LED with
Switch button

REQUIREMENT:

1. Arduino Board

2. Arduino IDE 1.05

3. Hook up wire

4. LED

5. Resistor

6. Bread Board

7. Switch Button

CONNECTION DIAGRAM:

82
Connection Diagram for controlling LED using Switch button

Algorithm:

1. Start
2. Define Constants:
o const int BUTTON = 2;
o const int LED = 3;
3. Variable Declaration:
o int buttonState = 0;
4. Setup Function:
o Configure BUTTON as INPUT_PULLUP.
o Configure LED as OUTPUT.
5. Main Loop:
o Begin Infinite Loop:
 Read BUTTON state into buttonState.
 If buttonState is LOW:
 Set LED HIGH (turn LED ON).
 Else:
 Set LED LOW (turn LED OFF).
o End Infinite Loop

PROGRAM:
const int BUTTON = 2;
const int LED = 3;
int buttonState = 0;
void setup() {
pinMode(BUTTON, INPUT_PULLUP); // Use internal pull-up resistor for button
pinMode(LED, OUTPUT);

83
}
void loop() {
buttonState = digitalRead(BUTTON);
if (buttonState == LOW) { // Button is active LOW with internal pull-up
digitalWrite(LED, HIGH); // Turn on LED
} else {
digitalWrite(LED, LOW); // Turn off LED
} }
PROCEDURE
Step 1: Make the connection with necessary components as per the pin configuration
Step 2: Click the open-source Arduino Software (IDE) and write the code.
Step 3: The connection is given as per the connection diagram.
Step 4: Upload the sketch to the Arduino Uno board.
Step 5: Click the Upload icon to upload the code to the Arduino board.
Step 6: If "Done uploading" appears at the bottom of the window, it means the sketch has
been successfully uploaded.
Step 7: When the switch button is pressed LED is ON and when it is released, LED is OFF.

84
RESULT:

Thus the program for using built in functions for accessing switch and LEDs, by using Arduino
Development Board is developed.

ARDUINO BASED PROGRAM TO MONITOR

Ex.No.8 ROOM TEMPERATURE USING TEMPERATURE Date:


SENSOR
AIM:

To design an embedded hardware module to measure the temperature and to display the result
in Serial Monitor, by using Arduino Development Board.

REQUIREMENT:

1. Arduino Board

2. Arduino IDE 1.05

3. HCSR-0A

4. Hook up wire

5. Temperature sensor(LM 35)

6. Bread board

THEORY:

85
 The Temperature Sensor LM35 series are precision integrated-circuit temperature devices with an
output voltage linearly proportional to the Centigrade temperature.

 The LM35 device has an advantage over linear temperature sensors calibrated in Kelvin, as the user
is not required to subtract a large constant voltage from the output to obtain convenient Centigrade
scaling.

 The LM35 device does not require any external calibration or trimming to provide typical accuracies
of ±¼°C at room temperature and ±¾°C over a full −55°C to 150°C temperature range.

CONNECTION DIAGRAM:

Connection Diagram of Temperature Sensor

86
Algorithm
1. Start
2. Declare variable `temp` as float
3. Initialize serial communication at baud rate 9600 in setup function
- Serial.begin(9600);
4. Begin loop function
- Enter infinite loop
a. Read analog input from pin A0
- temp = analogRead(A0);
b. Convert analog reading to temperature in Celsius
- temp = temp * 0.48828125;
c. Output temperature to serial monitor
- Print "TEMPERATURE: " to serial monitor
- Serial.print("TEMPERATURE: ");
- Print value of temp to serial monitor
- Serial.print(temp);
- Print unit "°C" and move to new line
- Serial.println("*C");
d. Delay for 1000 milliseconds
- delay(1000);
5. End loop function
6. End

PROGRAM:
float temp; // Variable to store temperature in Celsius
void setup() {
Serial.begin(9600); // Initialize serial communication at baud rate 9600
}
void loop() {
temp = analogRead(A0); // Read analog input from pin A0 (0-1023)
temp = temp * 0.48828125; // Convert analog reading to temperature in Celsius
// Print temperature to serial monitor
Serial.print("TEMPERATURE: ");
Serial.print(temp); // Print temperature value
Serial.println("*C"); // Print unit (Celsius) and move to new line
delay(1000); // Delay for 1 second before taking next temperature reading
87
}

PROCEDURE

Step 1: Make the connection with necessary components as per the pin configuration

Step 2: Click the open-source Arduino Software (IDE) and write the code.

Step 3: The connection is given as per the connection diagram

Step 4: Upload the sketch to the Arduino Uno board

Step 5: Click the Upload icon to upload the code to the Arduino board.

Step 6: If "Done uploading" appears at the bottom of the window, it means the sketch has
been successfully uploaded.

Step 7: Temperature sensor LM 35 senses the room temperature continuously and it is displayed in the serial
communication port.

OUTPUT:

88
RESULT:
Thus an embedded hardware module is designed to monitor the temperature by using Arduino
Development Board.

ARDUINO BASED PROGRAM TO CONTROL


Ex.No.9 Date:
SERVO MOTOR

AIM:

To design an embedded hardware module for servo motor control by using Arduino
Development Board.

REQUIREMENT:

1. Arduino Board

2. Arduino IDE 1.05

3. Servo motor

4. Hook up wire

THEORY:

 A Servo Motor is a small device that has an output shaft. This shaft can be positioned to specific

89
angular positions by sending the servo a coded signal.

 As long as the coded signal exists on the input line, the servo will maintain the angular position of the
shaft. If the coded signal changes, the angular position of the shaft changes.

 Servos are used in radio-controlled airplanes to position control surfaces like the elevators and
rudders. They are also used in radio-controlled cars, puppets, and of course, robots.

 The servo motor has some control circuits and a potentiometer (a variable resistor, aka pot)
connected to the output shaft.

 If the shaft is at the correct angle, then the motor shuts off. If the circuit finds that the angle is not
correct, it will turn the motor until it is at a desired angle.

 The output shaft of the servo is capable of traveling somewhere around 180 degrees.

 A normal servo is used to control an angular motion of 0 to 180 degrees. It is mechanically not
capable of turning any farther due to a mechanical stop built on to the main output gear.

 The power applied to the motor is proportional to the distance it needs to travel. So, if the shaft
needs to turn a large distance, the motor will run at full speed.

 If it needs to turn only a small amount, the motor will run at a slower speed. This is
called proportional control

CONNECTION DIAGRAM:

90
Connection Diagram of Servo motor control

Algorithm:

1. Start
2. Include Servo Library:
o #include <Servo.h>
3. Declare Servo Object:
o Create a Servo object named servo1
4. Setup Function:
o Attach servo1 to digital pin 9 (servo1.attach(9);)
5. Main Loop (loop Function):
o Set servo to 90 degrees (servo1.write(90);)
o Delay for 1 second (delay(1000);)
o Set servo to 180 degrees (servo1.write(180);)
o Delay for 1 second (delay(1000);)
o Set servo to 0 degrees (servo1.write(0);)
o Delay for 1 second (delay(1000);)
o Sweep servo from 0 to 180 degrees in steps of 2 degrees
 Begin loop:
 Increase servo position (position += 2)
 Set servo to current position (servo1.write(position);)
 Short delay for smooth movement (delay(20);)
 End loop when position reaches 180 degrees
o Sweep servo from 180 to 0 degrees
 Begin loop:
 Decrease servo position (position -= 1)
 Set servo to current position (servo1.write(position);)
91
 Short delay for smooth movement (delay(20);)
 End loop when position reaches 0 degrees

PROGRAM:
#include <Servo.h> // Include the Servo library
Servo servo1; // Create a Servo object named servo1
void setup() {
servo1.attach(9); // Attach the servo to digital pin 9
}
void loop() {
int position; // Variable to store servo position
// Move servo to specific positions and pause
servo1.write(90); // Set servo to 90 degrees position
delay(1000); // Pause for 1 second
servo1.write(180); // Set servo to 180 degrees position
delay(1000); // Pause for 1 second
servo1.write(0); // Set servo to 0 degrees position
delay(1000); // Pause for 1 second
// Sweep servo from 0 to 180 degrees
for (position = 0; position < 180; position += 2) {
servo1.write(position); // Set servo to current position
delay(20); // Short delay for smooth movement
}
// Sweep servo from 180 to 0 degrees
for (position = 180; position >= 0; position -= 1) {
servo1.write(position); // Set servo to current position
delay(20); // Short delay for smooth movement
}
}

PROCEDURE
Step 1: Make the connection with necessary components as per the pin configuration
92
Step 2: Click the open-source Arduino Software (IDE) and write the code.
Step 3: The connection is given as per the connection diagram.
Step 4: Upload the sketch to the Arduino Uno board.
Step 5: Click the Upload icon to upload the code to the Arduino board.
Step 6: If "Done uploading" appears at the bottom of the window, it means the sketch has
been successfully uploaded.
Step 7: The servo motor is placed at positions 0, 90 and 180 .

RESULT:

Thus an embedded hardware module is designed for servo motor control by using Arduino
Development Board.

ARDUINO BASED PROGRAM TO CONTROL


Ex.No.10 Date:
STEPPER MOTOR
93
AIM:

To design an embedded hardware module for stepper motor control application by using Arduino
Development Board.

REQUIREMENT:

1. Arduino Board

2. Arduino IDE 1.05

3. 1x bipolar Stepper motor

4. Hook up wire

5. Bread board

6. Power Supply

THEORY:

 A Stepper Motor or a step motor is a brushless, synchronous motor, which divides a full rotation
into a number of steps. Unlike a brushless DC motor, which rotates continuously when a fixed DC
voltage is applied to it, a step motor rotates in discrete step angles.

 The Stepper Motors therefore are manufactured with steps per revolution of 12, 24, 72, 144, 180,
and 200, resulting in stepping angles of 30, 15, 5, 2.5, 2, and 1.8 degrees per step. The stepper
motor can be controlled with or without feedback.

 A regular DC motor spins in only direction whereas a Stepper motor can spin in precise
increments.

 Stepper motors can turn an exact amount of degrees (or steps) as desired. This gives total control
over the motor, allowing to move it to an exact location and hold that position.

 It does so by powering the coils inside the motor for very short periods of time. The disadvantage
is that to power the motor all the time to keep it in the position that you desire

CONNECTION DIAGRAM:

94
Connection Diagram of Stepper motor control

PROGRAM:

// initialize the stepper library on pins 8 through 11:


Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0; // number of steps the motor has taken
void setup() {
// nothing to do inside the setup
}
void loop() {
// read the sensor value:
int sensorReading = analogRead(A0);
// map it to a range from 0 to 100:
int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
95
// set the motor speed:
if (motorSpeed > 0) {
myStepper.setSpeed(motorSpeed);
// step 1/100 of a revolution:
myStepper.step(stepsPerRevolution / 100);
}
}

PROCEDURE

Step 1: Make the connection with necessary components as per the pin configuration

Step 2: Click the open-source Arduino Software (IDE) and write the code.

Step 3: The connection is given as per the connection diagram.

Step 4: Upload the sketch to the Arduino Uno board.

Step 5: Click the Upload icon to upload the code to the Arduino board.

Step 6: If "Done uploading" appears at the bottom of the window, it means the sketch has

been successfully uploaded.

Step 7: The stepper motor rotates in clockwise and anticlockwise direction with the specified
delay.

RESULT:

Thus, an embedded hardware module is designed for stepper motor control application by using
Arduino Development Board.

96
ARDUINO BASED PROGRAM TO FIND
Ex.No.11 Date:
DISTANCE OF DISTANT OBJECT USING
ULTRA SONIC SENSOR

AIM:

To design an embedded hardware module to measure the distance between the Object and
the sensor, and to display the result in Serial Monitor, by using Arduino Development Board.

REQUIREMENT:

1. Arduino Board

2. Arduino IDE 1.05

3. HCSR-04 ultrasonic sensor

4. Hook up wire

THEORY:

Ultrasonic sensors work on a principle similar to radar or sonar which evaluate attributes of a
target by interpreting the echoes from radio or sound waves respectively. Ultrasonic sensors generate
high frequency sound waves and evaluate the echo which is received back by the sensor. Sensors
calculate the time interval between sending the signal and receiving the echo to determine the distance
to an object.
The timing diagram of HC-SR04 is shown below. To start measurement, Trig of SR04 must receive a
pulse of high (5V) for at least 10us, this will initiate the sensor will transmit out 8 cycle of ultrasonic burst
at 40kHz and wait for the reflected ultrasonic burst. When the sensor detected ultrasonic from receiver, it
will set the Echo pin to high (5V) and delay for a period (width) which proportion to distance. To obtain
the distance, measure the width (Ton) of Echo pin.

Time = Width of Echo pulse, in µS (micro second)


 Distance in centimeters = Time / 58
 Distance in inches = Time / 148

97
Timing Diagram of HC SR 04

CONNECTION DIAGRAM:

Connection Diagram of Ultrasonic Sensor

98
Algorithm:
 Start
 Initialize:
 Define TRIG_PIN as 13 and ECHO_PIN as 12 for respective digital pins.
 Set BAUD_RATE to 9600 for serial communication.
 Setup Function:
 Configure TRIG_PIN as OUTPUT and ECHO_PIN as INPUT.
 Begin serial communication at BAUD_RATE.
 Main Loop (loop() function):
 Set TRIG_PIN LOW initially.
 Delay for 2 microseconds.
 Send a 10-microsecond HIGH pulse to TRIG_PIN and then turn it LOW.
 Measure the duration of the pulse received on ECHO_PIN using pulseIn().
 Calculate distance in centimetres using the formula.
 If duration is 0, print "Warning: no pulse from sensor".
 Otherwise, print "Distance to nearest object: " followed by distance and " cm".
 Delay for 1 second before repeating the measurement.
 End

PROGRAM:
const unsigned int TRIG_PIN = 13; // Trigger pin connected to digital pin 13
const unsigned int ECHO_PIN = 12; // Echo pin connected to digital pin 12
const unsigned int BAUD_RATE = 9600; // Serial communication baud rate

void setup() {
pinMode(TRIG_PIN, OUTPUT); // Set TRIG_PIN (digital pin 13) as output
pinMode(ECHO_PIN, INPUT); // Set ECHO_PIN (digital pin 12) as input
Serial.begin(BAUD_RATE); // Initialize serial communication at BAUD_RATE
}
void loop() {
digitalWrite(TRIG_PIN, LOW); // Ensure trigger pin is low initially
delayMicroseconds(2); // Short delay before triggering
digitalWrite(TRIG_PIN, HIGH); // Send a 10 microsecond high pulse to trigger
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW); // Turn off the trigger pulse
const unsigned long duration = pulseIn(ECHO_PIN, HIGH); // Measure the duration of the echo pulse
int distance = duration / 29 / 2; // Convert the echo time to distance in centimeters (speed of sound is
approximately 29 microseconds per centimeter)
if (duration == 0) {
99
Serial.println("Warning: no pulse from sensor"); // Print a warning if no echo pulse received
} else {
Serial.print("Distance to nearest object: ");
Serial.print(distance); // Print the calculated distance
Serial.println(" cm"); // Print units (centimeters)
}
delay(1000); // Wait for 1 second before taking the next measurement
}

PROCEDURE

Step 1: Make the connection with necessary components as per the pin configuration

Step 2: Click the open-source Arduino Software (IDE) and write the code.

Step 3: Upload the sketch to the Arduino Uno board

Step 4: Click the Upload icon to upload the code to the Arduino board.

Step 5: If "Done uploading" appears at the bottom of the window, it means the sketch has
been successfully uploaded.

Step 6: If the object is detected the luminance of the LED varies.

Step 7: If you want to check the corresponding value changes, open the Serial Monitor and the
data changes in the window with respect to object detected distance.

RESULT:

Thus an embedded hardware module is designed to detect the distance of any object and created
an alerting message through luminance of the LED, by using Arduino Development Board.

100
A MINI PROJECT USING INTEL GALILEO
Ex.No.12 Date:
(HEALTH MONITORING SYSTEM)

AIM:
Design A Mini Project Intel Galileo

MINI PROJECT NAME:


Health Monitoring System using Arduino UNO R3

REQUIREMENTS:
 Breadboard
 Arduino UNO
 16x2 LCD Display
 I2C
 LM 35 Temperature Sensor
 Heart Rate Pulse Sensor
 Generic Jumper Wires

THEORY:
1. LM35 is a temperature sensor which can measure temperature in the range of -55°C
to 150°C. It is a 3-terminal device that provides analog voltage proportional to the
temperature. Higher the temperature, higher is the output voltage.

2. The principle behind the working of the Heartbeat Sensor is Photoplethysmograph.


Usually, the source of light in a heartbeat sensor would be an IR LED and the
detector would be any Photo Detector like a Photo Diode, an LDR (Light Dependent
Resistor) or a Photo Transistor.

CIRCUIT DIAGRAM
101
PROGRAM:
#include<Wire.h>
#include <LiquidCrystal_I2C.h>
int ThermistorPin = A1;
int Vo;
float R1 = 10000;
float logR2, R2, T ,Tc, Tf;
float c1 = 1.009249522e-03, c2 = 2.378405444e-04, c3 = 2.019202697e-07;
LiquidCrystal_I2C lcd(0x27, 16, 2);
double alpha=0.75;
int period=20;
double refresh = 0.0;
void setup()
{
pinMode(A0,INPUT);
lcd.begin();
lcd.backlight();
lcd.clear();
lcd.setCursor(0,0);
}
void loop()
102
{
static double oldValue=0;
static double oldrefresh=0;
int beat = analogRead(A0);
double value = alpha*oldValue+(0-alpha)*beat;
Vo = analogRead(ThermistorPin);
R2 = R1 * (1023.0 / (float)Vo - 1.0);
logR2 = log(R2);
T = (1.0 / (c1 + c2*logR2 + c3*logR2*logR2*logR2));
Tc = T - 253.15;
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Body: ");
lcd.print(Tc);
lcd.print((char)223);
lcd.print("C");
lcd.setCursor(0,1);
lcd.print("Heart: ");
lcd.print(beat/10);
oldValue=value;
oldrefresh=refresh;
delay(period*10);
delay(5000);
}

PROCEDURE

Step 1: Make the connection with necessary components as per the pin configuration

Step 2: Click the open-source Arduino Software (IDE) and write the code.

Step 3: Upload the sketch to the Arduino Uno board

Step 4: Click the Upload icon to upload the code to the Arduino board.

Step 5: If "Done uploading" appears at the bottom of the window, it means the sketch has
been successfully uploaded.

103
Step 6: If the object is detected the luminance of the LED varies.

Step 7: If you want to check the corresponding value changes, open the Serial Monitor and the
data changes in the window with respect to object detected distance.

OUTPUT:

RESULT:
Thus the Mini Project Health Monitoring System Detects the Body Temperature
and Heart Pulse Rate and displays in the LCD display , using Arduino UNO R3

104
CONTENT BEYOND SYLLABUS

105
EX NO: 01 MINI PIANO Date:

AIM:

To design a Mini Piano module using seven push button and buzzer on Tinkercad simulation tool

and write a program.

REQUIREMENT:

1. Online Tinkercad tool

CONNECTION DIAGRAM:

Connection diagram of Mini Piano

Algorithm

 Start

 Pin Initialization:

106
 Set pin 4, 5, 6, 7, 8, 9, and 10 as INPUT.
 Set pin 12 as OUTPUT for tone generation.

 Main Loop ( function):

 Check if digital pin 4 is LOW:


o If true, generate a tone of 240 Hz on pin 12 for 1000 milliseconds.
 Check if digital pin 5 is LOW:
o If true, generate a tone of 270 Hz on pin 12 for 1000 milliseconds.
 Check if digital pin 6 is LOW:
o If true, generate a tone of 300 Hz on pin 12 for 1000 milliseconds.
 Check if digital pin 7 is LOW:
o If true, generate a tone of 338 Hz on pin 12 for 1000 milliseconds.
 Check if digital pin 8 is LOW:
o If true, generate a tone of 360 Hz on pin 12 for 1000 milliseconds.
 Check if digital pin 9 is LOW:
o If true, generate a tone of 400 Hz on pin 12 for 1000 milliseconds.
 Check if digital pin 10 is LOW:
o If true, generate a tone of 450 Hz on pin 12 for 1000 milliseconds.
 Add a small delay (10 milliseconds) to improve performance.

 End

PROGRAM:
void setup()
{
pinMode(4, INPUT);
pinMode(12, OUTPUT);
pinMode(5, INPUT);
pinMode(6, INPUT);
pinMode(7, INPUT);
pinMode(8, INPUT);
pinMode(9, INPUT);
pinMode(10, INPUT);
}
void loop()
{
if (digitalRead(4) == 0) {
tone(12, 240, 1000); // play tone 46.5 (undefined3 = 240 Hz)
}

107
if (digitalRead(5) == 0) {
tone(12, 270, 1000); // play tone 48.52 (undefined4 = 270 Hz)
}
if (digitalRead(6) == 0) {
tone(12, 300, 1000); // play tone 50.37 (undefined4 = 300 Hz)
}
if (digitalRead(7) == 0) {
tone(12, 338, 1000); // play tone 52.41 (undefined4 = 338 Hz)
}
if (digitalRead(8) == 0) {
tone(12, 360, 1000); // play tone 53.51 (undefined4 = 360 Hz)
}
if (digitalRead(9) == 0) {
tone(12, 400, 1000); // play tone 55.34 (undefined4 = 400 Hz)
}
if (digitalRead(10) == 0) {
tone(12, 450, 1000); // play tone 57.4 (undefined4 = 450 Hz)
}
delay(10); // Delay a little bit to improve simulation performance
}

PROCEDURE

Step 1: Create an account on Tinkercad online simulation tool

Step 2: Click the circuit tab appears on the screen and create new circuit.

Step 3: Basic components needed for the design appears on the right side of the screen.

Step 4: Drag the necessary components and complete the design

Step 5: Complete the design and write the code or build the blocks based on the logic by clicking the

code icon.
Step 6: Complete the code and verify it by clicking the simulation button appears in the screen.

Step 7: If the circuit and program are correct it shows the result in the screen otherwise it shows

108
warning message.

RESULT:

109
Thus the Mini Piano module was designed using seven push button, Arduino board & buzzer on
Tinkercad simulation tool and it is verified

EX NO: 02 AUTOMATIC SANITIZATION TUNNEL Date:

AIM:

To design an automatic sanitization tunnel on Tinkercad simulation tool and write a program.

REQUIREMENT:

1. Online Tinkercad tool

CONNECTION DIAGRAM:

Connection diagram of automatic sanitization tunnel


Algorithm
 Start
 Pin Initialization:
 Set digital pin 6 as INPUT.
 Set digital pins 11, 12, and 13 as OUTPUT.
 Main Loop (function):
110
Check if digital pin 6 is HIGH
o If true, then:
 Set digital pins 11 and 13 HIGH
 Set digital pin 12 LOW
 Delay for 5000 milliseconds
o If false (pin 6 is LOW), then:
 Set digital pins 11 and 13 LOW
 Set digital pin 12 HIGH
 End

PROGRAM:
void setup()

pinMode(6, INPUT);
pinMode(11, OUTPUT);
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
}

void loop()

if (digitalRead(6) == 1)

digitalWrite(11, HIGH);

digitalWrite(13, HIGH);
digitalWrite(12, LOW);
delay(5000);
}

else

digitalWrite(11, LOW);
digitalWrite(13, LOW);
digitalWrite(12, HIGH);
}
111
}

PROCEDURE

Step 1: Create an account on Tinkercad online simulation tool

Step 2: Click the circuit tab appears on the screen and create new circuit.

Step 3: Basic components needed for the design appears on the right side of the screen.

Step 4: Drag the necessary components and complete the design

Step 5: Complete the design and write the code or build the blocks based on the logic by clicking the

code icon.

Step 6: Complete the code and verify it by clicking the simulation button appears in the screen.

Step 7: If the circuit and program are correct it shows the result in the screen otherwise it shows

Warning message.

RESULT:

Thus the automatic sanitization tunnel was designed on Tinkercad simulation tool and it is
verified

112

You might also like