Professional Documents
Culture Documents
MICROCONTROLLERS LAB
BTCS14F4800
SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY
Name
SRN
Branch
Semester
Section
Academic Year
Demonstrate an ability to use both polling and interrupt-driven approaches for interfacing
Design interfaces to external devices connected to the microcontroller using a standard bus
Lab Requirements
Following are the required hardware and software for this lab, which is available in the laboratory.
Hardware: Desktop system with windows OS installed. Presently in the Lab, 8051
Development boards and interface kits, 8051 programmer, CRO.
Software: KeilC51-compiler. 8051 Flash Burner.
This microcontroller programming manual can be read simply as a text; however it is intended to
be interactive. That is, you should be compiling, modifying and using the programs that are
presented herein.
Project Explorer
(Tree Menu) Editor Window
Build Window
c. Type the example code listed below into the new window.
d. This program will toggle Ports 1 and 2 with a delay.
ORG 0H
MOV A, #55H
AGAIN:
MOV P1, A
MOV P2, A
ACALL DELAY
CPL A
SJMP AGAIN
DELAY:
MOV R3, #200
OUTER: MOV R2, #0255
INNER: DJNZ R2, INNER
DJNZ R3, OUTER
RET
END
c. A new window should port will pop up. This represent the Port andPins
d. Step through the code by pressing F11 on the Keyboard. The Parallel Port 1 Box
should change as you completely step through the code.
e. To exit out, Click on Debug Menu and Select Start/Stop Debug Session
AT89C51ED2 Microcontroller
The AT89C51RD2/ED2 retains all of the features of the Atmel 80C51 with 256 bytes of internal
RAM, a 5 source 4-level interrupt controller and three timer/counters. TheAT89C51ED2 provides
2048 bytes of EEPROM for nonvolatile data storage. In addition, the AT89C51RD2/ED2 has a
Programmable Counter Array, an XRAM of 1792bytes, a Hardware Watchdog Timer, SPI
interface, Keyboard, a more versatile serial channel that facilitates multiprocessor communication
(EUART) and a speed improvement mechanism (X2 Mode).
The fully static design of the AT89C51RD2/ED2 allows reducing system power consumption by
bringing the clock frequency down to any value, including DC, without loss of data. The
AT89C51RD2/ED2 has 2 software-selectable modes of reduced activity and an 8-bitclock pre-
scalar for further reduction in power consumption. In the Idle mode the CPU is frozen while the
peripherals and the interrupt system are still operating. In the Power-down mode the RAM is
saved and all other functions are inoperative.
The added features of the AT89C51RD2/ED2 make it more powerful for applications that need
pulse width modulation, high speed I/O and counting capabilities such as alarms, motor control,
corded phones, and smart card readers.
Description: The AT89C51ED2 contains a non-volatile 64KB on-chip flash program/data memory that is
both parallel programmable and serial In-system and In-application programmable. The device supports 6-
clock/12-clock mode selection by programming a flash bit using parallel programming or In-system
programming. The instruction set is compatible with 80C51 instruction set.
Features:
a. 80C51 Central Processing Unit
- 64K Bytes On-chip Flash Program/Data Memory
- 256 Bytes Scratch Pad RAM
- On-chip 1792 bytes Expanded RAM (XRAM)
b. In-System Programmable (ISP) Flash memory
c. 12-clock operation with selectable 6-clock operation (via In-System Programming or via
parallel programmer)
d. On-chip 2048 Bytes EEPROM Block for Data Storage – 100K Write Cycle
e. Power control modes:
- Clock can be stopped and resumed
- Idle mode
- Power-down mode
f. Two speed ranges
- 0 to 20 MHz with 6-clock operation
- 0 to 33 MHz with 12-clock operation
g. Dual Data Pointers
h. Four interrupt priority levels
i. Eight interrupt sources
j. Four 8-bit I/O ports
k. Watchdog timer.
l. Full-duplex enhanced UART
- Framing error detection
- Automatic address recognition
m. Three 16-bit timers/counters T0, T1 (standard 80C51) and Additional T2 (capture and
compare)
n. Serial Peripheral Interface Module (SPI)
o. Programmable Counter Array
p. Asynchronous port reset
q. Low EMI (inhibit ALE, 6-clock mode)
r. Wake-up from Power Down by an external interrupt
Interrupt system:
The AT89C51ED2 has a total of 7 interrupt vectors, two external interrupts (/INT0and /INT1),
three timer interrupts (timer0, 1 and 2), the serial port interrupt, SPI interrupt and the PCA
interrupt.
Note
Windows environment: Programs can be edited, compiled and executed using Keil IDE.
All operations like opening a file, saving a file; compiling the program and executing the program
are listed under different menus inside the IDE. Keyboard shortcuts are also available for the
abovementioned operations.
Note: Every lab program in the manual includes problem statement, student learning outcomes,
theoretical description, source code listing, code description, expected results, compilation,
Logical errors, final program with results, assignment, and viva question.
CONTENTS
Sl. No. Lab Programs Page No.
Build an assembly language program for 8051 microcontroller to add,
1 02
subtract, multiply and divide 8-bit numbers.
Develop an assembly language program for 8051 microcontroller to
2 transfer a block of (𝑛 = 10 bytes) data from location 1000H to 07
location 1050H.
Create an assembly language program for 8051 microcontroller to sort
a given list of 𝑛 = 6 bytes of data in ascending or descending order
3 10
stored from location 9000H in external memory using bubble sort
algorithm.
Compose an assembly language program for 8051 microcontroller to
determine the largest or the smallest numbers in a list of 𝑛 = 6 bytes at
4 13
location 4000H and store the largest / smallest element at
location 4062H.
Construct an assembly language program for 8051 microcontroller to
add 10 BCD numbers stored in successive memory locations starting
5 from 20H in internal RAM locations and store the result at 16
address 40H (lower significant byte) and 41H (higher significant
byte).
Make up a C program for 8051 microcontroller to implement two bit
6 binary counter through port 2’s pin P2.4 and P2.5. Interface the output 19
on LEDs to show the realization.
Originate a C program to interface 7-segment display to 8051
7 microcontroller. Create a decimal up counter to count from 00 to 99 at 22
an update interval of 1 second.
Design an interface to connect a 4x4 matrix keypad to 8051
8 microcontroller. Plan a C program such that the keys pressed on the 27
keypad are displayed on the 7-Segment display.
Invent an interface to control a stepper motor through 8051
microcontroller. Compile a C program to rotate the stepper motor
9 clockwise and to rotate anticlockwise after an issue of external 33
interrupt at INT0 pin.
Device an interface to attach a digital to analog converter to 8051
10 microcontroller. Develop a C program to generate a sinusoidal wave 37
and display it on the CRO.
C program to reads an analog input and prints the voltage to the Serial
11 (A) 40
Monitor using Arduino Uno board.
11 (B) C program to implement an LED bar graph using Arduino Uno board. 41
Session 1
1 Problem Statement:
Build an assembly language program for 8051 microcontroller to add, subtract, multiply and
divide 8-bit numbers.
2 Student Learning Outcomes:
3 Theoretical Description:
There are separate programs written using assembly language to perform addition,
subtraction, multiplication and division. The data for the arithmetic operations given as
immediate in the instructions. To move the data into the registers, we need to use MOV
instruction. The arithmetic operations are accomplished using ADD, SUB, MUL and DIV
instructions. The results of the operations are moved to external memory.
4 Algorithm:
a. Algorithm Add: The following algorithm adds two 8 bit numbers and stores the result in
external memory.
1) Load the address of the external memory where the result is to be stored.
2) Load the first and second numbers to A and B registers respectively.
3) Add the numbers in the registers A and B.
4) Test for carry if generated, if so set register B to 1.
5) Store the result present in register A and carry in register B to the memory location set in
step 1.
b. Algorithm Sub: The following algorithm subtracts two 8 bit numbers and stores the
result in external memory.
1) Load the address of the external memory where the result is to be stored.
2) Load the first and second numbers to A and B registers respectively.
3) Subtract the number in register B from register A.
4) Test for borrow if generated, if so set register B to FF (indicates negative number).
5) Store the result present in register A and borrow in register B to the memory location set
in step 1.
c. Algorithm Mul: The following algorithm multiplies two 8 bit numbers and stores the 16
bit result in external memory.
1) Load the address of the external memory where the result is to be stored.
2) Load the first and second numbers to A and B registers respectively.
3) Multiply the numbers in the registers A and B.
4) Store the 16 bit result present in register A (lower byte) and in register B (higher byte) to
the memory location set in step 1.
d. Algorithm Div: The following algorithm divides two 8 bit numbers and stores the result
in external memory.
1) Load the address of the external memory where the result is to be stored.
2) Load the first and second numbers to A and B registers respectively.
3) Divide the number in register A by number in B.
4) Store the quotient present in register A and remainder in register B to the memory
location set in step 1.
5 Source Code Listing:
c. Multiplication:
1 ORG 0000H
2 MOV R0, #40H
3 MOV B,#5 ;B has 1st number
4 MOV A,#12 ;A has 2nd number
5 MUL AB ;16 bit product in AB with A having lower byte
6 MOVX @R0,A
7 INC R0
8 MOV A,B
9 MOVX @R0,A
10 HERE: SJMP HERE
11 END
d. Division:
1 ORG 0000H
2 MOV R0, #40H
3 MOV B,#2 ;B has 1st number
4 MOV A,#12 ;A has 2nd number
5 DIV AB
6 MOVX @R0,A
7 INC R0
8 MOV A,B
9 MOVX @R0,A
10 HERE: SJMP HERE
11 END
II: C Language Implementation
a. Addition:
#include <reg51.h>
void main( )
{
char xdata *sum = 0x40, xdata *carry = 0x41;
ACC = 60; B = 50;
*sum = ACC + B;
B = 0;
if (CY == 1) B++;
*carry = B;
}
b. Subtraction:
#include <reg51.h>
void main( )
{
char xdata *sum = 0x40, xdata *carry = 0x41;
ACC = 50; B = 30; CY = 0;
ACC = ACC - B;
*sum = ACC;
B = 0;
if (CY == 1) B = 0xFF;
*carry = B;
}
c. Multiplication:
#include <reg51.h>
void main()
{
char xdata *LSB = 0x40, xdata *MSB = 0x41;
ACC = 12;
B = 5;
ACC = ACC * B;
*LSB = ACC;
*MSB = B;
}
d. Division:
void main()
{
char xdata *QUO = 0x40, xdata *REM = 0x41;
ACC = 15;
B = 2;
ACC = ACC / B;
*QUO = ACC;
*REM = B;
}
6 Code Description:
a. Addition: The ADD instruction adds a byte value to the accumulator and stores the
results back in the accumulator. Several of the flag registers are affected.
Line 1: The ORG directive indicates the beginning of the address: 0000H
Line 2: Loads the external memory address.
Line 3, 4: Loads the operands in accumulator A and register B.
Line 5: Performs the addition operation.
Line 6: Loads B register with value 0; B indicates carry; set to zero if no carry.
Line 7: Transfers control to label SKIP if no carry flag is set after addition.
Line 8: If carry is set, register B is set to 1 to indicate the carry.
Line 9: Move the contents of accumulator A to external memory location address stored
in register R0.
Line 10: Increment the memory address in R0 to next location.
Line 11, 12:Move the contents of register B to external memory location address stored
in register R0.
Line 13: Loop the microcontroller at the same location.
Line 14: Indicates end of program.
b. Subtraction: The SUBB instruction subtracts the specified byte variable and the
carry flag from the accumulator. The result is stored in the accumulator. This
instruction sets the carry flag if borrow is required for bit 7 of the result. If no borrow
is required, the carry flag is cleared.
c. Multiplication: The MUL instruction multiplies the unsigned 8-bit integer in the
accumulator and the unsigned 8-bit integer in the B register producing a 16-bit
product. The low-order byte of the product is returned in the accumulator. The high-
order byte of the product is returned in the B register. The OV flag is set if the product
is greater than 255 (0FFh), otherwise it is cleared. The carry flag is always cleared.
d. Division: The DIV instruction divides the unsigned 8-bit integer in the accumulator
by the unsigned 8-bit integer in register B. After the division, the quotient is stored in
the accumulator and the remainder is stored in the B register. The carry and OV flags
are cleared.
If the B register begins with a value of 00h the division operation is undefined, the
values of the accumulator and B register are undefined after the division, and the OV
flag will be set indicating a division-by-zero error.
Note: The program explanation for subtraction, multiplication and division follows as
addition.
7 Expected Results:
Addition
Subtraction
Multiplication
Division
Session 2
1 Problem Statement:
Develop an assembly language program for 8051 microcontroller to transfer a block of (𝑛 = 10 bytes)
data from location 1000H to location 1050H.
3 Theoretical Description:
This assembly language program transfers 𝑛 = 10 bytes of data from location 1000𝐻 to
location 1050𝐻.The register DPTR is used to point to the external memory. The instruction
DJNZ is useful in looping.
4 Algorithm:
Algorithm Transfer: This algorithm transfers a block of data from a specified location
to another location in the external memory.
1) Initialize registers to hold count data & also the source & destination addresses.
2) Get data from source location into accumulator and transfer to the destination
location.
3) Decrement the count register and repeat step 2 till count is zero
5 Source Code Listing:
7 Expected Results:
Before Execution
Source
Memory
Address
Destination
Memory
Address
After Execution
Destination
Memory
Address
Session 3
1 Problem Statement:
Create an assembly language program for 8051 microcontroller to sort a given list of 𝑛 = 6 bytes of
data in ascending or descending order stored from location 9000H in external memory using bubble
sort algorithm.
2 Student Learning Outcomes:
3 Theoretical Description:
This sorts an array of n=6 bytes of data in ascending order stored from location 9000h using
bubble sort algorithm. For conditional statement instructions like JNC is used.
4 Algorithm:
Algorithm Sort: This algorithm transfers a block of data from a specified location to
another location in the external memory.
1) Store the elements of the array from the address 9000h
2) Initialize a pass counter with array size-1 count (for number of passes).
3) Load compare counter with pass counter contents & initialize DPTR to point to
the start address of the array (here 9000h).
4) Store the current and the next array elements pointed by DPTR in registers B and
r2 respectively.
5) Subtract the next element from the current element.
6) If the carry flag is set (for ascending order) then exchange the 2 numbers in the
array.
7) Decrement the compare counter and repeat through step 4 until the counter
becomes 0.
8) Decrement the pass counter and repeat through step 3 until the counter becomes 0.
5 Source Code Listing:
11 MOV R2,A
12 SUBB A,B ;Difference of two elements
13 JNC NOXCHG ;If first element is less no exchange
14 MOV A,B ;else exchange elements
15 MOVX @DPTR,A
16 DEC DPL
17 MOV A,R2
18 MOVX @DPTR,A
19 INC DPTR
20 NOXCHG: DJNZ R1,L2 ;Loop back
21 DJNZ R0,L1 ;Loop for rest of elements
22 HERE: SJMP HERE
23 END
II: C Language Implementation
void main()
{
char xdata *ptr = 0x9000;
int i,j,n = 6;
char temp;
for(i = 0; i < n-1; i++)
{
for(j = 0; j < n-i-1; j++)
{
if(ptr[j] > ptr[j + 1])
{
temp = ptr[j];
ptr[j] = ptr[j + 1];
ptr[j + 1] = temp;
}
}
}
}
6 Code Description:
Line 1: The ORG directive indicates the beginning of the address: 0000H
Line 2: Load R0 with size of array (𝑛 − 1)
Line 3: Set DPTR to point base address of the array.
Line 4, Line 5: Store contents of R0 in R1.
Line 6, Line 7: Load the first element in B.
Line 8: Point to next element in the array.
Line 9: Get next element in A.
Line 10: Clear the carry flag
Before Execution:
After Execution:
Session 4
1 Problem Statement:
Compose an assembly language program for 8051 microcontroller to determine the largest or
the smallest numbers in a list of 𝑛 = 6 bytes at location 4000H and store the largest /
smallest element at location 4062H.
2 Student Learning Outcomes:
3 Theoretical Description:
This program finds the largest element in a given array of 𝑛 = 6 bytes at location
4000ℎ and stores the element at location 4062ℎ.
4 Algorithm:
Algorithm Sort: This algorithm transfers a block of data from a specified location to
another location in the external memory.
1) Store the elements of the array from the address 9000h
2) Initialize a pass counter with array size-1 count (for number of passes).
3) Load compare counter with pass counter contents & initialize DPTR to point to
the start address of the array (here 9000h).
4) Store the current and the next array elements pointed by DPTR in registers B and
r2 respectively.
5) Subtract the next element from the current element.
6) If the carry flag is set (for ascending order) then exchange the 2 numbers in the
array.
7) Decrement the compare counter and repeat through step 4 until the counter
becomes 0.
8) Decrement the pass counter and repeat through step 3 until the counter becomes 0.
5 Source Code Listing:
7 Expected Results:
Before Execution:
After Execution:
Session 5
1 Problem Statement:
Construct an assembly language program for 8051 microcontroller to add 10 BCD numbers stored in
successive memory locations starting from 20H in internal RAM locations and store the result at
address 40H (lower significant byte) and 41H (higher significant byte).
3 Theoretical Description:
This program adds 10 BCD numbers stored in successive memory locations starting from 20H in
internal RAM locations and store the result at address 40H and 41H. To get the result in decimal DAA
instruction need to be used.
4 Algorithm:
Algorithm Large: This algorithm locates largest number among a set of numbers
stored in the external memory.
1) Store the elements of the array at address 4000h of external memory.
2) Store the length of the array in register R3 and set it as counter.
3) DPTR is loaded with starting address of the array.
4) Store the first number of the array in register R1 (R1 is assigned to hold the largest
number).
5) Increment DPTR.
6) Subtract the number pointed by DPTR from the contents of R1 (to compare
whether the next array element is larger than the one in R1).
7) If the element pointed by DPTR is larger; then load the larger number in to R1.
8) Decrement the counter and repeat through 5 until the counter becomes 0.
9) Store the largest number in R1 at address 4062h.
5 Source Code Listing:
}
else
flag = 0;
high = high << 4;
res = high + low;
return res;
}
6 Code Description:
Line 1: The ORG directive indicates the beginning of the address: 0000H
Line 2: Store the number of elements in R7 and set it as counter.
Line 3: R0 is loaded with starting address of the array (Memory pointer).
Line 4: Clear the memory location and set as Sum.
Line 5: Clear the memory location and set as Carry.
Line 6: Get the first number in A.
Line 7: Add contents of A with Sum.
Line 8: Adjust for BCD.
Line 9: Jump to label NEXT if no carry is generated.
Line 10: Increment contents of Carry if carry is generated.
Line 11: Store the result in Sum.
Line 12: Increment memory pointer to next number.
Line 13: Decrement the counter R7and repeat through label Back until the counter
becomes 0.
Line 14: Loop the microcontroller at the same location.
Line 15: Indicates end of program.
7 Expected Results:
Before execution:
After Execution:
Session 6
1 Problem Statement:
Make up a C program for 8051 microcontroller to implement two bit binary counter through port 2’s
pin P2.4 and P2.5. Interface the output on LEDs to show the realization.
3 Theoretical Description:
This program implements two bit binary counter. Make the connection from CN3 (PORT2)
to CN11 using 10 core FRC. Select SW2 switch to PROG mode. Download hex file using
FLIP 2.4.2. Then select SW2 switch to RUN mode and press SW1 reset switch.
The main principle of this experiment is to interface LEDs to the 8051 family micro
controller. Commonly, used LEDs will have voltage drop of 1.7v and current of 10mA to
glow at full intensity. This is applied through the output pin of the micro controller.
Light Emitting Diodes are the semiconductor light sources. Commonly used LEDs will have
a cut-off voltage of 1.7V and current of 10mA. When an LED is applied with its required
voltage and current it glows with full intensity. The Light Emitting Diode is similar to the
normal PN diode but it emits energy in the form of light. The color of light depends on the
band gap of the semiconductor. The following figure shows “how an LED glows?”
Thus, LED is directly connected to the AT89C51 microcontroller. The negative terminal of
the LED is connected to the ground through a resistor. Value of this resistor is calculated
using the following formula.
𝑅 = (𝑉 − 1.7)/10𝑚𝐴, where V is the input voltage.
Interface Circuit Diagram:
Generally, microcontrollers output a maximum voltage of 5V. Thus the value of resistor
calculated for this is 330 Ohms. Thus this can be connected either to the cathode or anode of
the LED.
4 Algorithm:
Algorithm Count: This algorithm implements 2 bit binary counter.
1) Initialize i to 0 and repeat thru step 5 until i < 4.
2) Shift the lower nibble of i to higher nibble and store it in k.
3) Call delay.
4) Move the contents of k to port P2 of the microcontroller.
5) Increment the contents of i.
5 Source Code Listing:
I: C Language Implementation
#include <reg51.h>
void delay (void);
void main()
{
unsigned char i, k;
while(1)
{
for(i=0x00; i<0x04; i++)
{
k = i<<4;
delay();
P2=k;
}
}
}
void delay(void)
{
unsigned int j, k;
for(j=0;j<30000;j++)
for(k=0;k<10;k++);
}
II: Assembly Language Implementation
1. ORG 1000H
2. L1: MOV R0, #00H
3. MOV R1, #03H
4. L2: MOV A, R0
5. SWAP A
6. MOV P2, A
7. ACALL DELAY
8. INC R0
9. DJNZ R1, L2
10. SJMP L1
11. END
6 Code Description:
The include statement imports the file "reg51.h" which defines the microcontroller’s port
definitions. This program contains two functions main() and delay(). The main function
generates the counts from 00 to 11 and puts them on port 2’s pin P2.4 and P2.5. Delay
School of Computing and Information Technology Page20
Microcontrollers Lab REVA University
function sets two nested for loops to delay between the counts.
7 Expected Results:
Session 7
1 Problem Statement:
Originate a C program to interface 7-segment display to 8051 microcontroller. Create a decimal up
counter to count from 00 to 99 at an update interval of 1 second.
3 Theoretical Description:
When this routine is executed the counting starts from 00 to 99 on 2-segment display
units (U18 to U19).
There are four multiplexed 7-segment display units (U16, U17, U18 and U19) on the board.
Each display has 8-inputs SEG-A (Pin-7), SEG-B (Pin-6), SEG-C (Pin-4), SEG-D (Pin-2),
SEG-E (Pin-1), SEG-F (Pin-9), SEG-G (Pin-10) and SEG-H (Pin-5) and the remaining pins
pin-3 & pin-8 are Common Cathode CC. These segments are common cathode type hence
active high devices. The port lines P0.4 to P0.7 are used to select one of the six digits as
shown in the table below. These signals P0.4 to P0.7 are used as inputs to the 74LS145 (U3)
and the output lines of the decoder are used as enable lines for six 7-segment displays. The
port lines P1.0 to P1.7 are used as segment lines for the six digits through the 74HCT244
buffer (U4).
Selection Of seven segment displays:
3 Algorithm:
I: C Language Implementation
#include <reg51.h>
unsigned char dig1 = 0x00, dig2 = 0x00;
unsigned char temp1 = 0x00, temp2 = 0x00; dig_count = 0x00;
int count = 0x00;
unsigned char led_code[10] = {0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};
bit tmr0_flg = 0, one_sec_flg = 0;
void timer0_init(void);
void Display(void);
void main(void)
{
timer0_init(); // Initialize the Timer-0
while(1)
{
while(tmr0_flg == 0);
tmr0_flg = 0;
dig_count ++;
if(dig_count == 0x02)
dig_count = 0x00;
if(one_sec_flg == 1)
{
one_sec_flg = 0;
dig1++;
if(dig1== 0x0A)
{
dig1 = 0;
dig2++;
if(dig2 == 0x0A)
dig2 = 0;
}
} //end of one_sec if
Display();
} //end of while(1)
} //end of main
void timer0_init(void)
{
TMOD = 0x01; // Timer0 is configured in Mode-1,
TL0 = 0xCC;
TH0 = 0xF8; // For 2.0 ms Delay
TCON = 0x00; // Clearing All Flags
ET0 = 1; // Enabling Timer0 Interrupt
TR0 = 1; // Turn ON the Timer0
EA = 1; // Enabling Global Interrupt
}
void timer0_isr(void) interrupt 1
{
TL0 = 0xCC; // Reloading Value into registers for every overflow
TH0 = 0xF8;
TF0 = 0; // Clearing Interrupt Flag
tmr0_flg = 1;
if(count == 500)
{
one_sec_flg = 1;
count = 0x00;
}
else count ++;
}
void Display(void) // To display on 7-segments
{
if(dig_count == 0x00) // For Segment U19
{
temp1 = dig1;
P0 = 0x30;
}
The include statement imports the file <reg51.h> which defines the microcontroller’s port
definitions. The program uses array_dec to store segment hex values of the digits. The
program also uses timer 0 configured in mode 1 to interrupt the microcontroller after some
time. The ISR timer0_isr() updated the flags after 1 second. The main function enables the
interrupts and initializes the timer 0 and set an infinite loop. Within the loop main function
generates the digits for the decimal counter and calls the display() function. The display()
function maps the digits to the segment hex values and transfers them to the seven segment
display. The lookup table for displaying 0 to 9 is as follows.
value h g f e d c b a Number
0x3F 0 0 1 1 1 1 1 1 0
0x06 0 0 0 0 0 1 1 0 1
0x5B 0 1 0 1 1 0 1 1 2
0x4F 0 1 0 0 1 1 1 1 3
0x66 0 1 1 0 0 1 1 0 4
0x6D 0 1 1 0 1 1 0 1 5
0x7D 0 1 1 1 1 1 0 1 6
0x07 0 0 0 0 0 1 1 1 7
0x7F 0 1 1 1 1 1 1 1 8
0x6F 0 1 1 0 1 1 1 1 9
SETUP – Make connections CN1 (PORT-0) to CN7 of 7-Segment Display block and
similarly CN2 (PORT-1) to CN8. Select SW2 switch to PROG mode. Download your .hex
file using FLIP 2.4.2. Then select SW2 switch to RUN mode and press SW1 reset switch.
When this routine is executed the counting starts from 00 up to 99. The counts are displayed
on the 7-segment displays U18 – U19. The counter is configured as up counter i.e.
incrementing numbers are displayed.
6 Expected Results:
Decimal counting from 00 to 99 on seven segment display units.
Session 8
1 Problem Statement:
Design an interface to connect a 4x4 matrix keypad to 8051 microcontroller. Plan a C program such
that the keys pressed on the keypad are displayed on the 7-Segment display.
3 Theoretical Description:
Program to demonstrate keyboard operation, takes a key from key board and displays
it on 7 Segment display.
The switches 0 to F are organized as 4 rows X 4 columns matrix. One end of all the switches
are connected to port lines P0.4 - P0.7, which is configured as columns. The other end of the
matrix is connected to the port lines P0.0 – P0.3 which is configured as rows. The interface
diagram for keypad is shown below. Operation: Initially take one column line to logic HIGH,
then check for each row. If first row is at logic '0' and other rows are at logic '1' then save the
read data and compare with the look-up table. Similarly repeat the procedure for all the
columns.
Interface Circuit Diagram:
4 Algorithm:
Algorithm Keypad: This algorithm senses a key pressed in 4x4 matrix keypad with
switches labeled 0 to F.
1) Begin.
2) Make All Pins High.
I: C Language Implementation
#include <reg51.h>
void scan(void);
void get_key(void);
void display(void);
void delay(int);
unsigned char scan_code[16] = { 0xEE, 0xDE, 0xBE, 0x7E,
0xED, 0xDD, 0xBD, 0x7D,
0xEB, 0xDB, 0xBB, 0x7B,
0xE7, 0xD7, 0xB7, 0x77 };
}
} // end of get_key();
void scan(void) // will return the scan code for the key pressed
{ // Both row lines and column lines are connected to Port 0
// Columns are connected to P0.4-P0.7 and P0.0-P0.3 are connected to rows
col = P0; //read port0, mask with 0xF0h
col &= 0xf0;
if(col != 0xf0) // Means a key is sensed
{
delay(30);
delay(30); // give some delay for debouncing
col = P0; // read the port again
col = col & 0xf0;
if(col != 0xf0) // debounce
{
flag = 1; // set the flag denoting a key is received
key = col | (row & 0x0f);
} // to get the scan code of the key pressed
else flag = 0x00;
}
} // end of scan()
void display(void)
{
P1 = result;
}
void delay(int i)
{
int j;
for(j = 0; j < i; j++);
}
II: Assembly Language Implementation
1. row equ 00h
2. col equ 01h
3. key equ 02h
4. result equ 03h
5. flag equ 00h
6. org 0100h
7. scan_c:db 0eeh, 0deh, 0beh, 07eh, 0edh, 0ddh, 0bdh, 07dh,
0ebh, 0dbh, 0bbh, 07bh, 0e7h, 0d7h, 0b7h, 077h
8. led_c: db 3fh, 66h, 7fh, 39h, 06h, 6dh, 6fh, 5eh,
5bh, 7dh, 77h, 79h, 4fh, 07h, 7ch, 71h
9. org 0000h
10. mov result, #3fh
11. main: acall getkey
12. acall disp
13. mov P3, #0ffh
14. sjmp main
15. getkey: acall disp
6 Code Description:
The include statement imports the file <reg51.h> which defines the microcontroller’s port definitions.
The program uses 4 functions; scan(), get_key(), display, and delay(). Two arrays, scan_code and
LED_CODE, holds the scan code of keypad and seven segment display codes. The main function sets
an infinite loop then invokes get_key() finction and display() function and also sets port P3 high. The
get_key() function calls scan() function. On sensing a key from scan() function get_key()
function will compare the received scan code with scan code lookup table and returns ASCII
code this function is in an eternal loop and will return to main() only after getting a key. The
get_key() function also obtains the corresponding seven segment display code. The scan()
function will return the scan code for the key pressed. Both row lines and column lines are
connected to Port 0. Columns are connected to P0.0-P0.3 and P0.4-P0.7 are connected to
rows. Rows are read from Port P0 in scan() function. The display function outputs the seven
segment display code mapped by get_key() function to port P1. The delay() function simply
introduces a delay.
SETUP - Make connections as per the below table using 10 core Flat Ribbon Cable.
Select SW2 switch to PROG mode. Download your .hex file using FLIP 2.4.2. Then select
SW2 switch to RUN mode and press SW1 reset switch. The keys 0 to F (keypad section)
pressed will display the corresponding Hexadecimal number on the MSB position of the
7-segment display (U16).
7 Expected Results:
The keys 0 to F pressed on the keypad will display the corresponding hexadecimal number on
the MSB position of the 7-segment display.
Session 9
1 Problem Statement:
Invent an interface to control a stepper motor through 8051 microcontroller. Compile a C program to
rotate the stepper motor clockwise and to rotate anticlockwise after an issue of external interrupt
at INT0 pin.
3 Theoretical Description:
Any of the 4 ports can be used for High Current applications where a stepper motor is
interfaced through the high current driver ULN2803. These lines will have high current (max
300mA) with low voltage level of 0.7V. The Stepper motor can be interfaced to the board by
connecting it to the Power mate PM1. The rotating direction of the stepper motor can be
changed. The direction of the rotation can be changed through software.
Interface Circuit Diagram:
4 Algorithm:
3) If Dir == 1 then
set Val = 0x08
Repeat for i=0 to 3
Move the contents of Val to output port P0
Right shift the bits of Val by 1 (Val = Val >>1)
Call delay function.
else
set Val = 0x01
Repeat for i=0 to 3
Move the contents of Val to output port P0
Left shift the bits of Val by 1 (Val = Val <<1)
Call delay function.
ISR Algorithm ChangeDir: This algorithm is an interrupt service routine that
complements the direction flag Dir on an external interrupt at pin INT0.
1) Complement the Dir flag (Dir = ~Dir)
Algorithm Delay(x): This algorithm generates a delay for the microcontroller.
Decrement the contents of x till x is zero.
5 Source Code Listing:
I: C Language Implementation
#include <reg51.h>
bit Dir=0;
void ChangeDir( void ) interrupt 0 /* Interrupt Vector at 0003H */
{
Dir = ~Dir; /* Complement the Direction flag */
}
void delay( unsigned int x ) /* Delay Routine */
{
for( ; x > 0; x--);
}
void main()
{
unsigned char Val,i;
EA=0x1; /* Enable Interrupt flag and Interrupt 0 */
EX0=0x1;
while(1)
{
if( Dir ) // If Dir Clockwise
{
Val = 0x08;
for(i=0;i<4;i++)
School of Computing and Information Technology Page34
Microcontrollers Lab REVA University
{
P0 = Val; // Write data for clock wise direction
Val = Val >> 1;
delay( 10000 );
}
}
else // AntiClockwise Direction
{
Val = 0x01;
for(i=0;i<4;i++)
{
P0 = Val; // Write data for anticlock wise direction
Val = Val << 1;
delay( 10000 );
}
}
}
}
II: Assembly Language Implementation
1. dir equ 00h
2. org 0000h
3. sjmp over
4. org 0003h
5. cpl dir
6. reti
7. over: clr dir
8. setb ea
9. setb ex0
10. again: jnb dir, anti
11. mov a, #08h
12. out0: mov P0, a
13. rr a
14. acall delay
15. cjne a, #08h, out0
16. sjmp again
17. anti: mov a,#01h
18. out1: mov P0,a
19. rl a
20. acall delay
21. cjne a, #01h, out1
22. sjmp again
23. delay: mov r3, #6
24. here2: mov r4, #255
25. here: djnz r4, here
Session 10
1 Problem Statement:
Device an interface to attach a digital to analog converter to 8051 microcontroller. Develop a
C program to generate a sinusoidal wave and display it on the CRO.
2 Student Learning Outcomes:
3 Theoretical Description:
DAC0800 is used to convert the digital data into analog signals. Digital data from any port is
given to DAC input. Amplitude of output waveform can be varied by varying the pot R39
that is by varying the reference voltage of DAC0800.
Interface Circuit Diagram:
4 Algorithm:
I: C Language Implementation
#include <reg51.h>
unsigned char sine_tab [49] = { 0x80, 0x90, 0xA1, 0xB1, 0xC0, 0xCD, 0xDA, 0xE5, 0xEE,
0xF6, 0xFB, 0xFE, 0xFF, 0xFE, 0xFB, 0xF6, 0xEE, 0xE5,
0xDA, 0xCD, 0xC0, 0xB1, 0xA1, 0x90, 0x80, 0x70, 0x5F,
0x4F, 0x40, 0x33, 0x26, 0x1B, 0x12, 0x0A, 0x05,
0x02, 0x00, 0x02, 0x05, 0x0A, 0x12, 0x1B, 0x26, 0x33,
0x40, 0x4F, 0x5F, 0x70, 0x80 };
int count;
void main ()
{
// This program is in a endless loop i.e. it executes the code within while(1) for ever.
// The program outputs different values corresponding different sine angles in hex
// to port P0.
// user can observe sine waveform at DAC output
while(1)
{
for(count=0;count<49;count++)
{
P0 = sine_tab[count];
}
}
}
II: Assembly Language Implementation
1. org 0000h
2. mov dptr, #sintab
3. again: mov r0, #00
4. nxt: mov a, r0
5. movc a, @a+dptr
6. mov P0, a
7. inc r0
8. cjne r0, #49, nxt
9. sjmp again
10. org 0100h
11. sintab: db 80h, 90h, 0A1h, 0B1h, 0C0h, 0CDh, 0DAh, 0E5h, 0EEh, 0F6h, 0FBh,
0FEh, 0FFh, 0FEh, 0FBh, 0F6h, 0EEh, 0E5h, 0DAh, 0CDh, 0C0h,
0B1h, 0A1h, 90h, 80h, 70h, 5Fh, 4Fh, 40h, 33h, 26h, 1Bh, 12h, 0Ah,
05h, 02h, 00h,02h,05h,0Ah,12h,1Bh,26h,33h,40h,4Fh,5Fh,70h,80h
12. end
School of Computing and Information Technology Page38
Microcontrollers Lab REVA University
6 Code Description:
The include statement imports the file <reg51.h> which defines the microcontroller’s port definitions.
The program uses an array sine_tab to store sine values in hex for different angles and also
variable count as an index variable for loop count. The main function sets an endless loop;
i.e. it executes the code within while (1) forever. The program outputs different values
corresponding to different sine angles in hex to port P0. The user can observe sine waveform
at DAC output.
SETUP – Make connections from CN1 (PORT0) to the connector CN15 of the ADC/DAC
block using a 10 core FRC. This connects the DAC0800 device to the microcontroller
through port PORT0. Select SW2 switch to PROG mode. Download hex file using FLIP
2.4.2. Then select SW2 switch to RUN mode and press SW1 reset switch. Observe the analog
output waveform at the pin-1 of RM10 (OUT1) and shorting jumper JP7 will make the output
wave form as single polar.
7 Expected Results:
Session 11 (A)
1 Problem Statement:
C program to reads an analog input and prints the voltage to the Serial Monitor using Arduino
Uno board
2 Student Learning Outcomes:
3 Theoretical Description:
Connect the three wires from the potentiometer to your board. The first goes to ground from one of
the outer pins of the potentiometer. The second goes to 5 volts from the other outer pin of the
potentiometer. The third goes from the middle pin of the potentiometer to analog input 2.
By turning the shaft of the potentiometer, you change the amount of resistance on either side of the
wiper which is connected to the center pin of the potentiometer. This changes the voltage at the center
pin. When the resistance between the center and the side connected to 5 volts is close to zero the
voltage at the center pin nears 5 volts.
5 Code Description:
A sketch is the name that Arduino uses for a program. It's the unit of code that is uploaded to
and run on an Arduino board. The structure of the sketch should have two mandatory
functions void setup() used for initialization and void loop() which holds the logic of the
program runs infinitely. This program reads from analog pin using analogRead() function,
coverts it to voltage and prints the result on the serial monitor by using Serial.println()
function.
6 Expected Results:
As the resistance is varied we should see its voltage across it on the serial monitor.
Eg: 0 ohms should display 0 volts
10K ohms should display 5 volts
Session 11(B)
1 Problem Statement:
C program to implement an LED bar graph using Arduino Uno board
2 Student Learning Outcomes:
3 Theoretical Description:
First we read the input. We map the input value to the output range, in this case ten LEDs.
Then we set up a for loop to iterate over the outputs. If the output's number in the series is
lower than the mapped input range, we turn it on. If not, we turn it off.
4 Source Code Listing:
// these constants won't change:
const int analogPin = A0; // the pin that the potentiometer is attached to
const int ledCount = 10; // the number of LEDs in the bar graph
void setup() {
// loop over the pin array and set them all to output:
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
pinMode(ledPins[thisLed], OUTPUT);
}
}
void loop() {
// read the potentiometer:
int sensorReading = analogRead(analogPin);
// map the result to a range from 0 to the number of LEDs:
int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);
5 Code Description:
The setup() function initializes all the LEDs connected to digital pins as OUTPUT. As and
when the potentiometer is varied the map() function maps the analog values to LED levels to
on or off the LEDs
6 Expected Results:
The LEDs will light up and down just like a volume indicator.
Session 12(A)
1 Problem Statement:
C program to control the position of a servo(DC motor) with a potentiometer on Intel Galileo
board
2 Student Learning Outcomes:
3 Theoretical Description:
Servo motors have three wires: power, ground, and signal. The power wire is typically red,
and should be connected to the 5V pin on the Intel board. The ground wire is typically black
or brown and should be connected to a ground pin on the board. The signal pin is typically
yellow or orange and should be connected to pin 9 on the board. The potentiometer should be
wired so that its two outer pins are connected to power (+5V) and ground, and its middle pin
is connected to analog input 0 on the board.
4 Source Code Listing:
#include <Servo.h>
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
myservo.write(val); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
}
5 Code Description:
Create servo object to control a servo. Attach the servo to Pin 9 by using attach() function part of
servo class. The map() function maps the DAC values to respective degree of rotation(0 o – 180o).
Finally send the degree to the servo using write() function.
6 Expected Results:
As the potentiometer is varied, the servo will rotate between 0o and 180o
Session 12(B)
1 Problem Statement:
C program to use a pushbutton to control an LED using Intel Galileo board
2 Student Learning Outcomes:
3 Theoretical Description:
Connect three wires to the board. The first two, red and black, connect to the two long vertical rows
on the side of the breadboard to provide access to the 5 volt supply and ground. The third wire goes
from digital pin 2 to one leg of the pushbutton. That same leg of the button connects through a pull-
down resistor (here 10K ohm) to ground. The other leg of the button connects to the 5 volt supply.
void setup() {
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output:
pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
In the setup() function we have to set button pin as INPUT and LED as OUTPUT. The loop() function
continuously reads the state of the button and toggles the LED based on the same.
6 Expected Results:
When the button is pushed the LED turns OFF if ON initially. Pushing again will toggle the state of
the LED.
Assignment Questions.
7 6 5 4 3 2 1 0