MD51 Lab Manual

80
MikroDes Systems Laboratory Manual MikroDes MD51 8051 trainer kit MikroDes Systems Web: www.mikrodes.com Email: [email protected] Phone: 09960933595, 02332305904 All Rights Reserved c 2010

description

8051 microcontroller Lab Manual. Useful for Lab Experiments.

Transcript of MD51 Lab Manual

Page 1: MD51 Lab Manual

MikroDesSystems

Laboratory Manual

MikroDes MD518051 trainer kit

MikroDes SystemsWeb: www.mikrodes.com

Email: [email protected]: 09960933595, 02332305904

All Rights Reserved c© 2010

Page 2: MD51 Lab Manual

MikroDesSystems

ii

MikroDes Systems gives no warranty of any kind, expressed or implied, with regard to thedocumentation in this manual. MikroDes Systems will not be liable for incidental or consequentialdamages in connection with, or arising out of the use of this documentation. The trainer kit MD51is to be used for educational purpose only and not as a part of any life saving device. This writeupis a property of MikroDes Systems. It may be used for academic purpose by customers of MikrodesSystems. Any part of this document should not be used for any commercial purpose.

All rights reserved.

For comments and suggestions contact: [email protected]

MikroDes Systems (www.mikrodes.com)

Page 3: MD51 Lab Manual

MikroDesSystems

List of Experiments

1 Keil microVision IDE 3

2 Implementing flashing LED 11

3 Implementing combinational logic 15

4 Sensing keys and activating relays 19

5 Reading code memory using MOVC instruction 25

6 BCD to 7-segment decoder using MOVC instruction 29

7 Study of Timer0 in timer mode 35

8 Study of Timer0 in counter mode 39

9 Study of LCD display 43

10 Sensing key in matrix keyboard 53

11 Study of external interrupts 61

12 Study of timer-0 interrupt 73

A Program Downloading Procedure 77

MikroDes Systems (www.mikrodes.com)

Page 4: MD51 Lab Manual

MikroDesSystems

2 List of Experiments

MikroDes Systems (www.mikrodes.com)

Page 5: MD51 Lab Manual

MikroDesSystems

Experiment 1

Keil microVision IDE

1.1 ObjectivesThe objectives of this experiment are,

1. To understand the various steps for creating a new project in Keil uVision IntegratedDevelopment Environment.

2. Build the project and Simulate the program.

1.2 Prerequisites1. Understanding of 8051 architecture2. MOV, SJMP instructions

1.3 Apparatus1. PC with Windows XP and Keil uVision installed2. 8051/89V51RD2 data sheet

1.4 TheoryFor developing 8051 based programs, we need following softwares

1. An editor: To type and edit the program2. An assembler: To convert an assembly program into object files3. A compiler: To convert a C program into object files4. A linker: To link all object files into a single object file5. Object to Hex converter: To convert the object file to hex file6. Debugger: For step-wise execution of the user program and understand the bugs7. Simulator: Imitates the functionality of on-chip peripherals such as timer, IO ports8. Downloader: To download the hex file into the microcontroller

The softwares (sr. 1 to sr. no 7) are available in a single integrated package. Such packageis typically called as Integrated Development Environment (IDE). An excellent IDE is availablefrom a company called Keil. The IDE is named as uVision (Micro Vision). Various versions ofuVision are available. You may download a demo copy of uVision latest version and install itin your PC for all experiments in this manual. All the programs given here are tested for KeiluVision-4. In addition to Vision-4 software (IDE), we also need software for downloading theuser program into the microcontroller. For 8051, a software called as FlashMagic is available.You may download the demo copy of it and install it in your PC for downloading hex files inMD51 kit. In this experiment, we are going to understand the uVision4 IDE.

1.5 ProcedureWe will have to carry out following three activities.

1. Activity 1: Creating a new uVision project

Page 6: MD51 Lab Manual

MikroDesSystems

4 Keil microVision IDE

2. Activity 2: Building the created project3. Activity 3: Simulating/Debugging the program

IMP: While doing any activity, read each point in the activity completely, and then do it.

1.5.1 Activity 1

1. Create a folder where all the files of your project will be stored. To do this, doubleclick on my computer icon. Open D: drive or any other available drive. For explanationpurpose, we consider here that, D: drive is available. After opening the drive, create anew folder “8051”. Open it and create one more folder. Name it as 01-FirstProj. Wewill keep all the files of our project in this folder. Remember.. Further in these activities,you need to create and save some files. Every time you do that, you MUST ensure thatthe file is saved in the SAME folder that you created just now. So the path of the folderfor this project is D:\ 8051\ 01-FirstProj.

2. Double click on the uVision4 icon on the desktop.3. This will start the uVision4 software. Close the open project (if any), by selecting the

Project menu and clicking on close. If there are no open projects, go to next step.4. Select the Project menu and click on New uVision Project (or New Project).5. Type the project file name. Do not provide any extension to the file name. The extension

of the file is automatically taken as .uvproj. For this exercise, give the name FirstProjto the project. Select the folder D:\8051\01-FirstProj. Then, click on Save.

6. The software now, prompts to select the microcontroller (device). The Mikrodes MD51kit uses P89V51RD2 microcontroller, Therefore, select the company as Philips (or NXP).Expand the device tree (i.e) click on the small + symbol on the left side of the com-pany name; and then select the device as P89V51RD2. Click on OK. (Do not selectP89LV51RD2 or similar other device. Select only P89V51RD2.) If you did not find thisdevice (i.e.) IC, then select Intel 8031 or 8051.

7. After this, the software prompts you to add the startup file. We do not need the startupfile now. Therefore click on the button No.

8. Now that we have created a new project, we need to create a source file (program file)(i.e.) the file which has the actual program. To do this, select the File menu and clickon New. A new file will be created. Now, select the File menu and click on Saveas. Provide the filename as main.asm. Remember this time, you must provide the fileextension. Since we are writing assembly program, give the .asm extension.

9. Select the folder D:\8051\01-FirstProj. Click on the Save button. The file is now savedwith the name main.asm. Now, type the program given in section 1.6 in this .asm fileand save the file. Save the file. (File→Save)

10. Now, open the project folder. (i.e.) D:\8051\01-FirstProj. Observe that a project filewith name “FirstProj.uvproj” and a program file with name “FirstProj.asm” are present.There are other files also; which are created by uVision4 software. Leave them as theyare.

11. Though the new source file is saved, it is not yet added to the project. To add thefile, expand Target1 in the project window. To see where is the project window referto figure 1.1. You will find it in the left portion of the figure. When you expand theTarget1, you will see Source Group 1 folder icon. Now, right click on the SourceGroup 1 and then click on the submenu Add files to the project. A dialog box willappear, prompting you to select the .c file. Since we have not created any .c file, andsince we have created .asm file, we have to select .asm file. For this, select the file type asASM Source file (*.s*, *.asm*, *.a*). When you do this, you will see FirstProj.asmfile. Click on it to select it, and click on the Add button ONLY ONCE. Click on closebutton to close the dialog box

MikroDes Systems (www.mikrodes.com)

Page 7: MD51 Lab Manual

MikroDes

Systems

Sect. 1.6 Program 5

1.6 Program

;*****************************************

; MikroDes Systems (www.mikrodes.com)

;

; Program for demonstating simple instructions

; bank switching and stack operation

; input: none

; output: none

; Procedure:

; build the project and simulate using Keil uVision4

; Single step the execution and observe the registers

; in memory window

;

; Copyright (c) MikroDes Systems Aug 2009

;*****************************************

; ORG is an assemble directive

ORG 0000H ; starting code address

SJMP START

ORG 0030H

; main program loop

START:

MOV A, #45H ; loads hex 45

MOV A, #45 ; loads decimal 45

CLR A ; clears ACC

; default bank is bank 0. So the value

; gets loaded at addr. 00

MOV R0, #55H

SETB RS0 ; select bank1

; this value gets loaded at 08 since

; R0 in bank1 has addr. 08

; observe location 08h in meory window.

MOV R0, #56H

; initialize SP before calling any subroutine

MOV SP, #35H

; observe SP(Stack Pointer) before LCALL,

; within the subroutine and after it

; Also observe the actual STACK

; (i.e.) location 35H onwards

PUSH ACC

PUSH ACC

POP ACC

POP ACC

LCALL subroutine

; infinite loop

MikroDes Systems (www.mikrodes.com)

Page 8: MD51 Lab Manual

MikroDesSystems

6 Keil microVision IDE

SJMP $ ;$

; subroutine

subroutine:

MOV A, #98H

RET

END; END is an assembly directive and not an instruction

1.6.1 Activity 2: Building the created project

1. Building a project means, converting the source files (.c or .asm) files into a hex filethat can be downloaded in the micro controller. Before we do this, we need to do somesettings for the project. For this, Select the Project menu and select Target options. Youmay also click on the target options icon. Refer to figure 1.1.

Figure 1.1: Setting target options

2. Set the crystal frequency as 11.0592 MHz, since the MD51 board uses this frequency.Refer to figure 1.2. After setting frequency, DONOT click OK, since we need to dosome more settings.

Figure 1.2: Setting clock frequency

3. Now, Click on the output tab. Click to select the option Create hex file. Refer tofigure 1.3. Click on OK button.

4. Select the Project menu and click on build target or press F7 key or click on buildicon on build tool-bar.

5. The project will be built (i.e.) the source file will be assembled. If there are no errors,the output window will show the message that there are 0 errors.

MikroDes Systems (www.mikrodes.com)

Page 9: MD51 Lab Manual

MikroDesSystems

Sect. 1.6 Program 7

Figure 1.3: Enabling Hex file Creation

Figure 1.4: Building Keil Project

Figure 1.5: Output after building the project

6. If there are any errors, they will be due to some mistake in typing the program. To locatethe error, double click on the first error. Check for the error and remove it. Repeat thistill all errors are removed. The output window will also show the name of the hex file.In our case it will be FirstProj.hex. (Observe that the hex file name is the SAME asthe project name and NOT the same as the .asm file) Save the program file and pressF7 to build the project again.

1.6.2 Activity 3: Simulating and debugging the program

Simulation means imitating the behavior of the processor in the software. Debugging meansto find bugs in your program by doing stepwise execution of your program. Once the projectis built without any errors, we can test the program by executing it step by step. This can bedone by entering in the debug mode. The screen will be as shown in the figure 1.6.

MikroDes Systems (www.mikrodes.com)

Page 10: MD51 Lab Manual

MikroDesSystems

8 Keil microVision IDE

1. To enter in the debug mode, press the debug icon, or press control+F5.

Figure 1.6: Debug mode

2. As soon as we enter the debug mode, the source code window shows an arrow on the leftside of the first instruction to be executed. Also the peripherals menu becomes activeand if we click on it, we can see various peripheral submenus.

3. If you see the disassembly window, then close it, since in this experiment we do not needit. Now, you will see only asm program in source code window.

4. Now, to execute the program in single step, click the step over button.

Figure 1.7: Program execution methods

5. The instruction at the arrow will be executed (simulated) and the arrow will move tothe next instruction.

6. Observe ACC and the registers R0, R1, ... R7 while executing the program. Notethat, the ACC and the registers get loaded by appropriate values. When RS0 bit is set,observe it by expanding the PSW register. Instead of separate RS0 and RS1 bits, thereis a RS. It indicates directly the bank selected. Observe that, when bank 1 is selected,R0 corresponds to memory location 08H, R1 (09H) and so on.IMP: If you have not studied the instructions given in this program, then skip next twopoints. The purpose of this experiments is mainly to get familier with uVision4 IDE.

7. Observe how SP gets initialized and how it is used to PUSH and POP the accumulator.After pushing observe internal data memory 35H onwards. Also observe that, PC ispushed on the stack while entering the subroutine and popped while exiting from it.

8. At the end of the program there is a statement for infinite loop. When this is executed,the program loops there itself. The instruction used for this is SJMP $.

1.7 Observations

Write the observations which you made, while single stepping the program.

1.8 Conclusions

Write conclusion about utility of simulator for debugging the programs.

MikroDes Systems (www.mikrodes.com)

Page 11: MD51 Lab Manual

MikroDesSystems

Sect. 1.9 Homework 9

1.9 Homework1. Read the help of uVision software and try to learn various facilities in it.2. Do enough practice of creating project, creating .asm file, building the project and sim-

ulating the program.

MikroDes Systems (www.mikrodes.com)

Page 12: MD51 Lab Manual

MikroDesSystems

10 Keil microVision IDE

MikroDes Systems (www.mikrodes.com)

Page 13: MD51 Lab Manual

MikroDesSystems

Experiment 2

Implementing flashing LED

2.1 ObjectivesThe objectives of this experiment are,

1. To understand the Input-output operations in 8051.2. To understand delay subroutine using DJNZ instruction.3. Debugging in uVision4.4. Downloading the program in MD51 kit.

2.2 Prerequisites1. Experiment 1, (Keil microVision IDE) should have been performed.2. DJNZ instruction

2.3 Apparatus1. PC with Windows XP2. Keil uVision and FlashMagic softwares installed3. 8051/89V51RD2 data sheet4. MD51 kit with power adapter and serial cable

2.4 Theory8051 micro-controller is a 40 pin chip. It has four ports. A port is nothing but a set of 8 pinswhich can used for data input-output(IO). The ports are named as P0, P1, P2 and P3. Theseports are brought onto pins of 8051. Since there are 8 pins per port, total 32 pins of 8051 canbe used as port lines. Each line can be individually made LOW or HIGH. Also the completeport (8 pins) can be written by an 8 bit data (byte). If the data written in the port is 00 then,the pins will become LOW and if the data written is FF, then, the pins will become HIGH. Ifthis is done repeatedly, it is possible to toggle the port pins; and if LEDs are connected to theport pins, the LEDs will flash.

This experiment explains how to perform port Output operations in 8051 and test it inMD51 kit. For this, we need to understand some instructions. So do the following activity.

2.4.1 Activity

Copy the syntax and description of following instructions from 8051 instruction set, (providedin the CD) and understand the operation of each instruction.

• MOV Addr,# Immediate Value• MOV Addr, Rn• MOV Rn, Addr• SETB, CLR instructions

Page 14: MD51 Lab Manual

MikroDesSystems

12 Implementing flashing LED

2.4.2 Outputting a byte on an 8-bit port

MOV Px, #<8 bit data> instruction can be used to write any value to any port. For example,for writing a value 35H in port P1, we should use MOV P1, # 35H. Here, # indicates animmediate value. (If # is not written, then 35H will be treated as an address). We can makethe micro-controller to wait by using a delay routine. After the delay routine we can againchange the port value and have another delay. If this is repeated, the port pins will toggle andthe LEDs connected to that port willl flash.

In MD51 kit, 8 LEDs are connected to port P1 in a pulled up fashion; (i.e.), if 00H is outputon P1, all LEDs will glow and if FFH is output on P1, all LEDs will be off. Refer to figure2.1. Observe that the cathodes of LEDs are connected to port P1 pins (P1.0, P1.1, ... P1.7).The DIP switch1 (DS4) is provided to disconnect the LEDs if required. In this experiment,you need to use the LEDs. So keep the DS4 switch ON. Also study the flowchart in figure 2.2and then the program given in section 2.7.

2.5 Circuit Diagram

23-Aug-2009 9:32:10 AM D:\mikrodes\projects\mikrodes\8051-trainerkit\8051 md51 kit\8051-Card.sch (Sheet: 3/3)

12

ON

R18

D16

R19

D18

R21

D20

R22

D21

R23

D22

R27

D23

R29

D24

R30

D25

3 412 DS4

P1.[0..7]

P1.

0

P1.

1

P1.

2

P1.

3

P1.

4

P1.

5

P1.

6

P1.

7

470E

,

470E

,

470E

,

470E

,

470E

,

470E

,

470E

,

470E

,

+5V

2-POS DIP Switch

Figure 2.1: LED Connections

1switches in Dual In-line Plastic package. These switches can fit in IC sockets

MikroDes Systems (www.mikrodes.com)

Page 15: MD51 Lab Manual

MikroDes

Systems

Sect. 2.6 Flowchart 13

2.6 Flowchart

Start

Make all port lines of P1 LOW

Wait for 1 sec

Make all port lines of P1 HIGH

Wait for 1 sec

Figure 2.2: Flowchart for Flash-LED

2.7 Program for flashing LED on P1;*****************************************

; LED Flashing program for 8051

; Tested with MD51 kit

; Copyright (c)

; MikroDes Systems

; http://www.mikrodes.com

; Aug 2009

;*****************************************

; ORG is an assemble directive to set

;the code memory address

ORG 0000H ; starting code address

SJMP BACK

ORG 0030H

; main program loop

BACK:

MOV P1, #00H

LCALL DELAY_1_SEC

MOV P1, #0FFH

LCALL DELAY_1_SEC

SJMP BACK

; subroutine for delay

MikroDes Systems (www.mikrodes.com)

Page 16: MD51 Lab Manual

MikroDesSystems

14 Implementing flashing LED

DELAY_1_SEC:

MOV R0, #55H

DLY2:

MOV R1, #55H

DLY1:

MOV R2, #55H

DJNZ R2, $ ;%$

DJNZ R1, DLY1

DJNZ R0, DLY2

RET

;*****************************************

2.8 Procedure1. Create a folder “8051” in D:\ and open it.2. Copy the folder “LED-flashing” from the “Programs” folder in the CD, to D:\8051.3. Open the folder D:\8051\LED-flashing. Double click to open the µVision project “LED-

flashing.uvproj”. The project will open in the µVision software.4. Build the project. This will crate a .hex file with name LED-flashing.hex5. Follow the instructions given in appendix A on page 77, and download the .hex file in

the micro-controller.6. After the downloading is complete, the user program starts executing. Observe that, the

LEDs connected to P1 start flashing. (Make sure that the DIP switch near LEDs is ON).

2.9 Exercise1. Change the immediate data 00h and 0FFH, in the given program, to some other value,

build the project, download the file, reset the kit and observe the output.2. In the program try to increase the delay. (Copy-paste the instruction, LCALL DE-

LAY 1 SEC)

2.10 Conclusion1. It is easy to write any desired byte into a micro-controller port using MOV instruction.2. By repeatedly changing the data on a port with some delay, it is possible to flash LEDs.

The delay can easily be changed by changing the program.3. Micro-controller based logic gates are very useful in low frequency applications as there

is flexibility in functioning of logic gates.

2.11 Homework1. Modify the program to create 1KHz waveform on all port pins of P1. Download it in the

MD51 kit and observe the output. You will find that all the LEDs are always glowing.How will you test that they are flashing?

2. Use SETB and CLR instructions to flash only one LED connected to P1.0 after every 1second. Test the program using MD51 kit.

MikroDes Systems (www.mikrodes.com)

Page 17: MD51 Lab Manual

MikroDesSystems

Experiment 3

Implementing combinational logic

3.1 Objectives

The objectives of this experiment are,

1. To understand how to implement any combinational logic using assembly program in8051 microcontroller.

2. Implement an AND gate and verify it in MD51 kit.

3.2 Prerequisites1. 8051 architecture2. Port structure of 80513. MOV, SJMP instructions4. JB, JNB instructions

3.3 Apparatus1. PC with Windows XP,Keil uVision and FlashMagic installed.2. 8051 instruction sheet

3.4 Theory

3.4.1 What is a combinational logic?

A combinational logic is a logic whose output depends totally on the present state of inputs.(i.e.) the output does not depend on the previous states of input. This kind of logic circuitdoes not contain any memory elements such as flip-flops. They contain only simple gateswithout feedback. The gates AND, OR, NOR, NAND, EX-OR, EX-NOR etc. are examples ofcombinational logic. Also combination of the basic gates to implement a Boolean expressionresults in a combinational logic.

3.4.2 Why to implement a combinational logic in microcontroller?

Many times, in industrial processes, the output state depends on the states of various inputs.In such case, we need to implement a combinational logic in a microcontroller. If we use adedicated circuit based on TTL or CMOS ICs, then the logic cannot be easily changed. (i.e.),this approach is not flexible. However, if the same logic is implemented using a microcontroller,then by just changing the assembly program, we can change the implemented logic. (i.e.)implementing a combinational logic in a microcontroller is a highly flexible way.So wherever, flexibility is more important, in such applications, it is better to implementcombinational logic in a microcontroller.

Page 18: MD51 Lab Manual

MikroDes

Systems

16 Implementing combinational logic

3.4.3 How to implement it?

To implement any combinational logic in a microcontroller, we need to configure some portpins as input and some as output. For example, if we want to implement a simple 2-inputAND gate, then we need to use two port pins as input and one port pin as output. In thisexperiment, we are going to use P3.2 and P3.3 as input lines and P1.0 as output. This isdone because, P3.2 and P3.3 port pins are connected to push to on switches which are placedin the right bottom corner of the MD51 kit. The output is taken from P1.0 since; LEDs areconnected to port P1.

Let s now try to implement an AND gate in 8051, using an assembly program. For this,the input-1 (P3.2) is first checked if it is logical 0 or 1. If it is 0, then the output P1.0 is madelogical 0. If it is 1, then next input, input2 (P3.3) is checked if it is logical 0 or 1. If it is 0,the output is made 0. If it is also 1, then it means both the inputs are 1. Hence the output ismade 1.

This way the logic of AND gate is implemented by continuously checking the inputs (calledas polling) and adjusting the output to either logic 1 or logic 0. The flowchart is shown infigure 3.1

Figure 3.1: AND gate flowchart

3.5 Program;*****************************************

; MikroDes Systems (www.mikrodes.com)

;

; Program for implementing 2 input

; AND gate in 8051

;

; input: keys S1(P3.2) and S2(P3.3) on the

; right bottom corner of MD51 kit

; output: LED connected to P1.0

; NOTE: Please note that the when the switch

; is pressed then, the logic level of input

MikroDes Systems (www.mikrodes.com)

Page 19: MD51 Lab Manual

MikroDesSystems

Sect. 3.6 Procedure 17

; is LOW and when released the logic level

; is HIGH.

; Also, the logic level of output is LOW when

; LED is glowing and it is HIGH when

; LED is OFF. This is because, the LEDs

; are connected with common anode mode.

; NOTE:

; (SWITCH=Pressed, pin=LOW)

; (SWITCH=Released, pin=HIGH)

; (LED=ON, pin=LOW) (LED=OFF, pin=HIGH)

; Procedure:

; Download the and_gate.hex using FlashMagic

; Press S1. Observe the LED (P1.0).

; It will not glow

; Press S2. Observe the LED (P1.0)

; It will not glow

; Press S1 & S2. Observe the LED (P1.0)

; It will glow now.

; Prepare the truth table and verify that

; the operation is same as AND gate.

; Copyright (c) MikroDes Systems Aug 2009

; www.mikrodes.com

;*****************************************

ORG 0000H ; starting code address

START:

JB P3.2, CLR_BIT ; jump to CLR_BIT if P3.2 is 0

JB P3.3, CLR_BIT ; jump to CLR_BIT if P3.2 is 0

CLR P1.0 ; set P1.0 if both P3.2 and P3.3 are 1

SJMP START

CLR_BIT:

SETB P1.0

SJMP START ; Repeat it

END

;*****************************************

3.6 Procedure

We will have to carry out following three activities.

1. Activity 1: Copy the folder of the experiment from the CD given. Open the project andstudy it.

2. Activity 2: Build the project, download the hex file in MD51 and verify the operation.3. Activity 3: Modify the program and verify functionality.

MikroDes Systems (www.mikrodes.com)

Page 20: MD51 Lab Manual

MikroDesSystems

18 Implementing combinational logic

3.6.1 Activity 1:

1. Create a folder “micro-controller” in D: drive (or in any local drive) and Open the createdfolder.

2. Insert the MikroDes MD51 CD in the CD drive and open it. Open the 8051 programsfolder. Copy the folder “03 AND-Gate” to the D:\micro-controller local folder. Aftercopying, open it.

3. Double click on “and gate.uvproj” file. This will start the uVision4 software and openthe project. Study the asm program in the file “AND-Gate.asm”. Build the project bypressing F7 key. The hex file will be created. Press Cntrol+F5 to start the simulation(debugging).

4. Click on Peripherals→IO port and then click on Port-1. This will show the port 1 state.(Refer to figure 3.2). Also open Port-3. Execute the program step-wise by typing F10,repeatedly. Set the port P3.2 and P3.3 and observe P1.0. Observe that, only when boththe inputs are 1 , the putput becomes 1 . This proves that, the program implements andAND gate in 8051.

Figure 3.2: Viewing ports in simulator

3.6.2 Activity 2:

1. Follow the instructions given in appendix A on page 77, and download the .hex file inthe micro-controller.

2. Now press the “push-to-on” switches S1 and S2 (near the right bottom corner of MD51kit) and observe P1.0 LED. You will find that, when both the switches are released, (i.e),when both inputs are logic 1 , the output becomes 1 . (i.e.) The LED becomes off. Forall other input combinations, the LED remains ON (P1.0 is logic 0 ). This proves that,the AND gate is implemented in 8051.

3.6.3 Activity 3:

1. Now, modify the program to implement OR gate by modifying the instructions. Repeatall steps of activity 2 and verify the operation in MD51 kit.

3.7 ObservationsWrite the observations which you made, while performing the activities mentioned.

3.8 ConclusionsWrite conclusion based on your observations.

3.9 HomeworkImplement EX-OR gate and verify its operation.

MikroDes Systems (www.mikrodes.com)

Page 21: MD51 Lab Manual

MikroDesSystems

Experiment 4

Sensing keys and activating relays

4.1 ObjectivesThe objectives of this experiment are,

1. To understand how to sense the state of a key connected to a port pin using assemblyprogram in 8051 micro-controller.

2. To understand how to activate relay based on the key state.

4.2 Prerequisites1. 8051 architecture2. Port structure of 80513. JB, JNB, SETB, CLR instructions

4.3 Apparatus1. PC with Windows XP, Keil uVision and FlashMagic installed.2. 8051 instruction sheet3. MD51 micro-controller kit

4.4 TheoryIn most of the electronic systems, the user input is taken through keys. The keys can beconnected to a micro-controller in two ways. 1. Single key per pin and 2. Key matrix.

In this experiment, we are going to understand the first method of connecting keys. Thereare two keys S1 and S2 on the MD51 kit and they are connected to P3.2 and P3.3. These keysare connected such that, when a key is pressed, the logic level on the corresponding pin goeslow and when the key is released, it goes high. A key can be sensed using the instructions JBor JNB. The syntax of JB is JB <bit address>, label. If we want to sense P3.2, and if wewrite an instruction JB P3.2, Next; then it will sense the port pin P3.2 and if the pin is high,then the program will jump to Next. Otherwise the program will go to the next instruction.JNB instruction works the same way except that it makes the program branch if the level onthe pin is low. Using these instructions it is possible to sense a key press event and based onit activate some devices.

In this experiment, we are going to activate/deactivate relays on the MD51 kit based onthe key state. There are 2 relays on the kit. They are Relay-0 and Relay-1. Relay-0 is drivenby pin P0.2 and Relay-1 is driven by the pin P0.3. The program given senses the keys S1 andS2 (near the right bottom corner) and activates Relay-0 is key INT-0 is pressed. If key S2(INT-1) is pressed, the Relay-1 is activated. The figure 4.1 shows the inputs and outputs. The8051 micro-controller senses the keys and based on the key state, activates the relays.

1. JB (Jump on bit):This instruction checks the specified bit and jumps to specified label if that bit is high.The syntax of the instruction is, JB bit, label.

Page 22: MD51 Lab Manual

MikroDesSystems

20 Sensing keys and activating relays

Figure 4.1: Block diagram

Key S1 (INT0) P3.2Key S2 (INT1) P3.3Relay-0 P0.2Relay-1 P0.3

Table 4.1: Pin Connections

2. JNB (Jump on no bit):This instruction checks the specified bit and jumps to specified label if that bit is low.The syntax of the instruction is, JB bit, label.

A relay can be activated by making LOW, the port pin, that is connected to relay driver.To deactivate the relay the port pin needs to be made HIGH. A port pin can be made HIGHor LOW, using following instructions.

1. SETB (Set the bit):This instruction sets the specified bit. If the bit is a port bit(for example, P1.0, P1.2etc), then, it sets the corresponding port pin (i.e. makes it HIGH). The syntax of theinstruction is, SETB bit.

2. CLR (Clear the bit):This instruction makes the specified bit low. If the bit is a port bit(for example, P1.0,P1.2 etc), then, it resets the corresponding port pin (i.e. makes it LOW). The syntax ofthe instruction is, CLR bit.

4.5 Circuit diagram

4.5.1 Key sensing circuit

The key sensing circuit is placed at the right bottom corner of the MD51 kit as shown in figure4.3(a). The actual connections are shown in figure 4.3(b). The circuit shows that, there aretwo push button keys S1 and S2. When a key is in released (not pressed) position, the upperpoint of that key goes to VCC potential. (i.e.) the logic level is HIGH. When a key is pressed,the upper point of that key goes to GND potential. (i.e.) the logic level is LOW. Key S1 isconnected to P3.2 and key S2 to P3.3 through the DIP switch DS8. Therefore, while doingthis experiment, both the switches in DS8 must be in ON position.

4.5.2 Relay control circuit

The relays, connectors for relay contacts and relay driver circuit are placed near top side ofthe MD51 kit as shown in figure 4.4(a). The actual circuit is shown in part (b) of the samefigure. The circuit shows that, there are two relays Relay-0 and Relay-1. They are driven

MikroDes Systems (www.mikrodes.com)

Page 23: MD51 Lab Manual

MikroDesSystems

Sect. 4.5 Circuit diagram 21

Figure 4.2: Relay Circuit

Figure 4.3: Key sensing section on MD51 kit

by the driver transistors Q1 and Q2 . The transistors are controlled by the port lines P0.2and P0.3 respectively. If P0.2 is made low then the relay-0 is activated else it is deactivated.Similarly P0.2 controls relay-1.

MikroDes Systems (www.mikrodes.com)

Page 24: MD51 Lab Manual

MikroDesSystems

22 Sensing keys and activating relays

Figure 4.4: Relay section in MD51 kit

4.6 Flow chartThe flowchart is shown in figure 4.5. In this flowchart, initially a key S1 is sensed. If itis pressed, then the relay-0 is activated, else the relay-0 is deactivated. Then the key S2 issensed. If it is pressed, then the relay-1 is activated, else the relay-1 is deactivated. Thecomplete process is repeated continuously.

Figure 4.5: Flowchart for relay control

MikroDes Systems (www.mikrodes.com)

Page 25: MD51 Lab Manual

MikroDes

Systems

Sect. 4.7 Program 23

4.7 Program

;*****************************************

; MikroDes Systems (www.mikrodes.com)

;

; THIS PROGRAM DEMONSTRATES RELAY CONTROL

; USING KEY INPUT

; input: Key press on S1 or S2

; output: activation of relay-0 / relay-1

; Procedure:

; Switch ON the DIP switches DS8 (bottom

; middle place) and also DS3 (near relay)

; Download the relay-control.hex file

; using FlashMagic

; *RESET* the kit.

; Press S1 or S2 and

; observe the relay state.

; Copyright (c) MikroDes Systems Aug 2009

; www.mikrodes.com

;****************************************

; equate used for making the program

; easy to read/understand

RLY_0 EQU P0.2

RLY_1 EQU P0.3

SW1 EQU P3.2

SW2 EQU P3.3

ORG 0000

SJMP START

START: ; This is a label

; DEACTIVATE BOTH RELAYS

SETB RLY_0

SETB RLY_1

; MAKE KEY PINS INPUT

SETB SW1

SETB SW2

BACK:

JNB SW1, RLY_0_ACTIVTE ; KEY NOT PRESSED

SETB RLY_0 ; DEACTIVATE

MikroDes Systems (www.mikrodes.com)

Page 26: MD51 Lab Manual

MikroDesSystems

24 Sensing keys and activating relays

CHK_RLY_1:

JNB SW2, RLY_1_ACTIVTE ; KEY NOT PRESSED

SETB RLY_1 ; DEACTIVATE

SJMP BACK

RLY_0_ACTIVTE:

CLR RLY_0

SJMP CHK_RLY_1

RLY_1_ACTIVTE:

CLR RLY_1

SJMP BACK

END

;****************************************

4.8 Procedure1. Create a folder “8051” in D:\ and open it.2. Copy the folder “Relay” from the “Programs” folder in the CD, to D:\ Micro-controller.3. Open the folder D:\ Micro-controller\Relay. Double click to open the µVision project

“Relay.uvproj”. The project will open in the µVision software.4. Build the project. This will crate a .hex file with name Relay.hex5. Follow the instructions given in appendix A on page 77, and download the .hex file in

the micro-controller.6. Press key S1 and observe that, relay-0 activates. If you release S1, the relay-0 is deacti-

vated. Also S2 controls relay-1 in similar way.

4.9 ObservationWhen key S1 is pressed, it is observed that, relay-0 activates. If S1 is released, the relay-0 isdeactivates. Also S2 controls relay-1 in similar way.

4.10 ConclusionIt is possible to sense a key connected to any port pin using JB and JNB instructions. It ispossible to activate any device such as relay, LED etc. using SETB and CLR instructions.

4.11 ExerciseThere are 8 LEDs on MD51 board. They are connected to P1.0 to P1.7. Write a program toactivate LED connected to P1.0 when key S1 is pressed and activate LED connected to P1.7when key S2 is pressed. Assemble the program, download and test it.

MikroDes Systems (www.mikrodes.com)

Page 27: MD51 Lab Manual

MikroDesSystems

Experiment 5

Reading code memory using MOVCinstruction

5.1 ObjectivesThe objectives of this experiment are,

1. To understand MOVC instruction2. To observe the 8051 code memory contents on LEDs

5.2 Prerequisites1. Understanding of 8051 architecture2. MOV, CPL, SJMP instructions

5.3 Apparatus1. PC with Windows XP and Keil uVision installed.2. 8051/89V51RD2 data sheet3. MD51 educational trainer kit, serial cable and power adapter

5.4 TheoryThe code memory of a microcontroller holds the op-codes of user program. The code memoryis a non-volatile memory. When we download the program in the actual microcontroller, it isloaded in the code memory. Through user program we can, however, read the code memory ifrequired. For this MOVC instruction is available in 8051. The syntax of the MOVC instructionis MOVC A, @A+DPTR.In this, the DPTR holds the base address and ACC (accumulator) holds the offset. Thisinstruction adds the A and DPTR to find the actual code memory address and the data atthat location is read and loaded in A. For example, the following program loads data fromaddress (0030H+04H = 0034H) and loads the data from this address from code memory intoAccumulator.

MOV A, #04H

MOV DPTR, #0030H

MOVC A, @A+DPTR

5.5 ProcedureWe will have to carry out following three activities.

1. Activity 1: Creating a new uVision project2. Activity 2: Building the created project3. Activity 3: Downloading and testing the program

Page 28: MD51 Lab Manual

MikroDes

Systems

26 Reading code memory using MOVC instruction

5.5.1 Activity 1:

Understand and write the syntax and operation of MOVC instruction.

5.6 ProgramIn, MD51 kit; the LEDs are connected to port P1. These LEDs can be used to observe thecontents of the code memory itself. If we want to observe the contents of location 0033H incode memory, then we can set the DPTR to 0030H and Accumulator to 03H. With these valuesin DPTR and ACC, if MOVC instruction is executed, then the accumulator will have the dataat location 0033H from code memory.

;*****************************************

; MikroDes Systems (www.mikrodes.com)

; This program reads the code memory and

; displays the op-codes of the program on Port 1

; Input: none

; Output: value on port P1.

; Procedure:

; Download the hex file CodeMemory.hex

; Reset the kit if required.

; The LEDs will show the value 90H. (1001 0000)

; This is the first byte of the instruction MOV DPTR, #00.

; To verify, enter the debug mode in uVision and observe

; the code memory by typing C:0x0000 in memory window

; modify the second instruction (MOV A, #00) to

; MOV A, #03 and save the file.

; Build the project. Download the hex file.

; The LEDs will show 74H. This is the byte at address

; 0003H in the code memory.

; Thus by setting the value of A or DPTR or both, we

; can read the byte at the desired code memory address

; (c) Copyright 2009 MikroDes Systems

; www.mikrodes.com

;********************************************************

; The program always starts from the location 0000H

ORG 0000H

; set the pointer to desired address

MOV DPTR, #0000H

; set the offset to the desired value

MOV A, #00H

; read the code memory from address A+DPTR

MOVC A, @A+DPTR ; Read the table

MikroDes Systems (www.mikrodes.com)

Page 29: MD51 Lab Manual

MikroDesSystems

Sect. 5.7 Observations 27

; output the 7 segment code on P1 LEDs

CPL A ; IMP: since the LEDs are connected

; as common anode, we need to complement the data

; Output the value in Acc to port P1.

MOV P1, A

; Infinite loop (equivalent to halt instruction)

SJMP $

END ;********************************************************

5.6.1 Activity 2:

1. Create a folder “8051” in D:\ and open it. If it already exists, open it.2. Copy the folder “05 Reading Code Memory” from the “8051 Programs” folder in the

CD, to D:\8051.3. Open the folder D:\8051\ 05 Reading Code Memory. Double click to open the Vision

project.4. “CodeMemory.uvproj”. The project will open in the Vision software.5. Build the project. This will create the .hex file in the project folder. Verify that it is

created.

5.6.2 Activity 3:

1. Follow the instructions given in appendix A on page 77, and download the .hex file inthe micro-controller.

2. Observe that, the LEDs connected to P1 show the pattern 10010000 (90H). This isbecause; the first byte of the instruction MOV DPTR, #0000H is 90H.

3. To observe this in simulator, click on view and then on memory window. Then typeC:0x0000 in the top text box of memory window and press “enter” key. This will showthe code memory. Observe that the value at location 0000 is 90H. Refer to figure 5.1.

4. In the program, DPTR and A are both set to 0000H and then the MOVC is executed.Therefore, the value in accumulator after MOVC is executed is value at 0000H (i.e.) 90H.

5. Change the value loaded in DPTR and/or accumulator. Build the project, then downloadthe program and observe the LEDs.

5.7 ObservationsWrite the observations which you made, while single stepping the program. Also write yourobservations after downloading the program in the MD51 kit.

5.8 ConclusionsWrite conclusion about using MOVC for reading the code memory.

5.9 HomeworkWrite a program to seqencially display first 4 bytes of code memory on LEDs connected to P1.

MikroDes Systems (www.mikrodes.com)

Page 30: MD51 Lab Manual

MikroDesSystems

28 Reading code memory using MOVC instruction

Figure 5.1: Viewing code memory in simulator

MikroDes Systems (www.mikrodes.com)

Page 31: MD51 Lab Manual

MikroDesSystems

Experiment 6

BCD to 7-segment decoder usingMOVC instruction

6.1 ObjectivesThe objectives of this experiment are,

1. To understand how to prepare 7 segment codes.2. To understand how to store and access BCD to 7-segment table in 8051.

6.2 Prerequisites1. Understanding of 8051 architecture2. MOV, MOVC, ANL, CPL, SJMP instructions3. Experiment 5 should have been performed

6.3 Apparatus1. PC with Windows XP and Keil uVision installed.2. 8051/89V51RD2 data sheet3. MD51 educational trainer kit, serial cable and power adapter

6.4 TheoryBCD stands for Binary Coded Decimal. This is a way of representing numbers in 4-bit binaryvalue for numbers between 0 and 9. Seven segment code is used to show a number on a7-segment LED display. The conversion from BCD to 7-segment is many times required todisplay a number on a seven segment display. The BCD to 7 segment conversion process isillustrated in figure 6.1. It shows that the input is 4 bit BCD value and the output is 7 segmentdata and also decimal point. (total 8 bit output).

Figure 6.1: Block diagram of BCD to 7 segment conversion

A seven segment display has 7 segments (a, b, c, d, e, f, g) and a decimal point (dp).Therefore it requires total 8 bit data. The 8 bit data is usually connected to 7 segment displaysuch that the bit 0 (D0) is connected to segment a, D1 is connected to segment b and so on.

Page 32: MD51 Lab Manual

MikroDesSystems

30 BCD to 7-segment decoder using MOVC instruction

There are two kinds of 7-segment displays; Common anode (CA) and Common cathode(CC) type. The following table shows codes for both types. In this experiment, we assumethat we are using a common anode type display. Observe that, the 7-segment code for CCtype is just complement of that of CA type. Also observe that, the BCD value does not decidethe state of dp. This is because; whether decimal point is to be displayed or not; is decidedby the user depending on the number of decimal places in the displayed number. Figure 6.2shows the BCD to 7 segment table.

Figure 6.2: BCD to 7 segment table

6.4.1 Activity 1:

1. Write the BCD codes for numbers 0 to 9.2. Understand the concept of common anode and common cathode connections. Draw the

internal connections of 7-segment display.3. Understand the codes given in the figure 6.2.

6.4.2 How to write the program?

Look at figure 6.2. Is there any fixed relationship between BCD input and 7-segment output?We do not find such a relation from the table. Such input output relation can be easilyimplemented with a microcontroller program using a Look-up table. A look-up table is nothingbut a table which can be accessed using the base address and an offset.

Look-up table is usually stored in code memory since the code memory is non-volatile. Tostore the table in the code memory, we need to use the DB assembler directive. This directivetells the assembler to put the given data at appropriate code memory address. Lets understandby an example.

ORG 0423H

MY_TABLE:

DB 0C0H, 0F9H, 0A4H

The above program first sets the code memory address to 0423H. Therefore the value ofthe label MY TABLE will be 0423H. The assembler will prepare the .hex file such that, thevalue C0H will get stored at address 0423H, value F9H at 0424H and so on, in code memory.

6.4.3 Activity 2

1. Prepare a look-up table for common anode 7-segment display.

MikroDes Systems (www.mikrodes.com)

Page 33: MD51 Lab Manual

MikroDes

Systems

Sect. 6.5 Procedure 31

2. Study MOVC instruction of 8051. The syntax is MOVC A, @A+DPTR.

MOVC instruction reads the data at address A+DPTR, from the code memory. Whileusing MOVC, we need to set DPTR to the starting address (base address) of the table. Thiscan be dome using following instruction.

MOV DPTR, #MY_TABLE

Then we have to initialize A with any value between 0 and 9. (MOV A, #0H) and then wehave to access the table using the instruction MOVC A, @A+DPTR. If A=0, then after thisinstruction A will have value C0H. If A=1, then after this instruction A will have value F9Hand so on.

The following program takes the BCD data from lower nibble of P2 (P2.0, P2.1, P2.2 andP2.3), converts it to appropriate 7-segment code and displays the code on LEDs connected toport P1. This program actually can take values from 0-F. So it can display 7-segment codesfor all numbers 0 to F.

IMP: The program uses the leftmost column of the matrix keyboard for inputting the inputdata. Thus we want to use the matrix keyboard as simple 4 keys. We can do a simple trickfor this. In the matrix keyboard, keep the leftmost column line (P2.7) always low. This willmake the leftmost 4 column keys as simple 4 keys connected to lower nibble of P2. Therefore,in the program you can see the CLR P2.7 instruction.

6.5 ProcedureWe will have to carry out following three activities.

1. Activity 1: Creating a new uVision project2. Activity 2: Building the created project3. Activity 3: Simulating/Debugging the program

6.6 Program;*******************************************************

; MikroDes Systems (www.mikrodes.com)

; This program converts BCD value to 7 Segment code

; Input: P2.0-P2.3

; The input is to be given using leftmost column

; of the matrix keyboard. In this case,

; Uppermost key works as highest significant input

; Lowermost key works as lowest significant input

; Output: P1.0-P1.7

; The 7 segment code is displayed on LEDs connected

; to P1.

; Procedure:

; Download the bcd7seg.hex file using FlashMagic

; Reset the kit if required.

; You will observe pattern 1 0 0 0 1 1 1 0 on

; the LEDs. This pattern is corresponding to the

; BCD input F (refer to the table at the end of this

MikroDes Systems (www.mikrodes.com)

Page 34: MD51 Lab Manual

MikroDes

Systems

32 BCD to 7-segment decoder using MOVC instruction

; program)

; Now press keys on leftmost column of the keyboard

; and observe the LED pattern

; Correlate your observations with the table given

; at the end of the program.

; IMP:

; When switch is pressed, the logic level is LOW

; Copyright (c) MikroDes Systems Aug 2009

; www.mikrodes.com

;********************************************************

ORG 00H

SJMP START

ORG 30H

START:

; set P0.7 Low for making Matrix keyboard appear

; as simple 4 key keyboard

CLR P0.7

; Now use 4 the keys in column 0 to input BCD data.

; DPTR is used as base register. So it must be initialized by

; the start address of 7 segment table

MOV DPTR, #TABLE

LOOP:

; read the keys

MOV A,P2 ; Read the data from port 1

ANL A, #0FH ; Keep only lower nibble since the

;rows of the keyboard are connected to P2.0 to P2.3

MOVC A, @A+DPTR ; Read the table

; output the 7 segment code on P1 LEDs

CPL A ; imp: since the LEDs are connected to VCC

MOV P1, A

SJMP LOOP

TABLE:

DB 0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8

DB 0x80,0x90,0x88,0x80,0xC6,0xC0,0x86,0x8E

END

;********************************************************

; Seven segment table data

; The 7 seg display is assumed to be common anode type,

; directly connected to the port pins

; The segnment will glow if the connected pin is made LOW

; DP G F E D C B A

; 1 1 0 0 0 0 0 0 = 0xC0; for 0000 (0) all keys pressed

; 1 1 1 1 1 0 0 1 = 0xF9; for 0001 (1) upper three keys pressed

; 1 0 1 0 0 1 0 0 = 0xA4; for 0010 (2)

; 1 0 1 1 0 0 0 0 = 0xB0; for 0011 (3)

; 1 0 0 1 1 0 0 1 = 0x99; for 0100 (4)

MikroDes Systems (www.mikrodes.com)

Page 35: MD51 Lab Manual

MikroDesSystems

Sect. 6.7 Observations 33

; 1 0 0 1 0 0 1 0 = 0x92; for 0101 (5)

; 1 0 0 0 0 0 1 0 = 0x82; for 0110 (6)

; 1 1 1 1 1 0 0 0 = 0xF8; for 0111 (7)

; 1 0 0 0 0 0 0 0 = 0x80; for 1000 (8)

; 1 0 0 1 0 0 0 0 = 0x90; for 1001 (9)

; 1 0 0 0 1 0 0 0 = 0x88; for 1010 (A)

; 1 0 0 0 0 0 0 0 = 0x80; for 1011 (B)

; 1 1 0 0 0 1 1 0 = 0xc6; for 1100 (C)

; 1 1 0 0 0 0 0 0 = 0xCO; for 1101 (D)

; 1 0 0 0 0 1 1 0 = 0x86; for 1110 (E) lowest key pressed

; 1 0 0 0 1 1 1 0 = 0x8E; for 1111 (F) all keys released

;*********************************************************

6.6.1 Procedure

1. Create a folder “8051” in D:\ and open it. If it already exists, open it.2. Copy the folder “05 BCD-7SEG” from the “8051 Programs” folder in the CD, to D:\8051.3. Open the folder D:\8051\05 BCD-7SEG. Double click to open the Vision project “05

BCD-7SEG.uvproj”. The project will open in the Vision software.4. Build the project. This will create the .hex file in the project folder. Verify that it is

created.5. Connect the male side of serial cable to serial connector (near right top corner) on MD51

kit and female side of the serial cable to COM1 of PC.6. Follow the instructions given in appendix A on page 77, and download the .hex file in

the micro-controller.7. Observe that, the LEDs connected to P1 show the pattern 10001110. This is because;

all the keys in the leftmost column are in released state. (i.e.) the lower nibble of P2is 1111 (hex F). In the look-up table (figure 6.2), the output pattern for 1111 input is10001110.

8. Now press the lower key in the leftmost column of keyboard. The input pattern will be0111 (E). The output pattern on the LEDs will be 10000110.

9. Now, press the four keys of the left most column with any combination, and observethe LED pattern. Remember that, when a key is pressed the level on corresponding pinis low. Verify that the pattern on LEDs is the same as shown in look-up table in theprogram.

6.7 ObservationsWrite the observations that you made while doing this experiment.

6.8 ConclusionsWrite conclusion based on the observations.

6.9 HomeworkImplement a 3 to 8 decoder using look-up table method.

MikroDes Systems (www.mikrodes.com)

Page 36: MD51 Lab Manual

MikroDesSystems

34 BCD to 7-segment decoder using MOVC instruction

MikroDes Systems (www.mikrodes.com)

Page 37: MD51 Lab Manual

MikroDesSystems

Experiment 7

Study of Timer0 in timer mode

7.1 ObjectivesThe objectives of this experiment are,

1. To understand Timer in 80512. To create time delay using timer3. To display incrementing number on LEDs

7.2 Prerequisites1. Understanding of 8051 architecture2. MOV, CPL, SJMP instructions3. Experiments 1 to 4 should have been performed

7.3 Apparatus1. PC with Windows XP and Keil uVision installed.2. 8051/89V51RD2 data sheet3. MD51 educational trainer kit, serial cable and power adapter

7.4 TheoryThe 8051 microcontroller has two timers; Timer0 and Timer1. The timers are implementedin hardware; hence they can do the work of counting input clock pulses even when the micro-controller is doing some other work. When the timer is working with internal clock then itis said to work in “Timer” mode. This mode is useful for measuring time. When the timeris used with external clock, it is said to be in “counter” mode. This mode is useful to countnumber of external events; hence the counter mode can be used to implement event counter.The timers in Intel 8051 are incrementing type. They cannot be used in decrementing mode.There are total 4 modes of operation of timer in 8051.

1. Mode 0: 13 bit timer/counter2. Mode 1: 16 bit timer/counter3. Mode 2: 8 bit auto-reload mode4. Mode 3: implements three 8 bit timers using two 16 bit timers

In this experiment, we are going to configure the timer0 as timer in mode 1. In this mode,we will create a time delay of 1 second and, this time delay will be further used to showincrementing value on port P1.

The mode 1 of timer0 is a 16 bit mode. Hence it uses TH0 and TL0 together as 16 bittimer register. These registers are to be loaded separately as 8-bit registers.

To create a one second delay, we actually create a 50mSec delay and repeat it 20 times,thus creating 1 sec delay. To create, the basic 50 mS delay, we need to find the count to beloaded in the timer.

Page 38: MD51 Lab Manual

MikroDes

Systems

36 Study of Timer0 in timer mode

The MD51 kit uses a 11.0592MHz crystal. This is internally divided by 12 and then thatfrequency is fed to timer as clock. So timer gets the clock of (11.0592MHz)/12 = 0.9216 MHz(nearly 1 MHz). At this clock, the timer must increment by 50000 x 0.9216 pulses to get delayof 50mS. So the count comes to be 50000 x 0.9216 = 46080. We want the timer to overflowafter these many pulses. Therefore we have to load the timer by a value (FFFFh − 46080).Higher byte of this value is to be loaded in TH0 and lower byte in TL0. Once this is donethe timer is started and the timer flag bit TF0 is continuously checked till TF0 becomes 1.After this the timer is reloaded by (FFFFh − 46080). This is repeated 20 times. After timeroverflows 20 times, the time delay of 1 sec will be over.

7.4.1 Activity 1

Draw the block diagram of timer0 in mode 1, in figure 8.1 in your notebook.

Figure 7.1: Timer0 block diagram

From the above block diagram, we can understand that, to use the timer0 as timer in mode1, we have to clear the C/T bit. Then we have to clear GATE bit. Also we have to set theTR0 bit.

7.4.2 Activity 2

Read the program, comments and understand the program.

7.5 Program;****************************************

; THIS PROGRAM DEMONSTRATES TIMER-0 USED AS

; TIMER: Tested on MD51 V1.0 kit

; input: No input required

; output: binary count on LEDs (P1)

; Procedure:

; Download the hex file and observe the output

; on LEDs. The LEDs show incrementing count

; upto 10 and resets

; Copyright (c) Aug 2009

MikroDes Systems (www.mikrodes.com)

Page 39: MD51 Lab Manual

MikroDesSystems

Sect. 7.6 Procedure 37

; MikroDes Systems, Sangli

;*************************************************

ORG 0000

SJMP START

START:

MOV P1, #0FFH; ALL LEDs OFF

; 30H is used as count value to be displayed on LEDs

MOV 30H, #0

; Timer overflows 20 times

MOV 31H, #20

; Timer 0 set in mode 1

; and works as timer

MOV TMOD, #01; 0000 0001

MOV TL0, #LOW(0xFFFF-46080) ; count for 50mS delay

MOV TH0, #HIGH(0xFFFF-46080) ; count for 50mS delay

SETB TR0

BACK:

JNB TF0, $ ; wait till timer overflows

CLR TF0 ; clear the flag

; reload the timer

MOV TL0, #LOW(0xFFFF-46080) ; count for 50mS delay

MOV TH0, #HIGH(0xFFFF-46080) ; count for 50mS delay

DJNZ 31H, BACK ; repeat 20 times

MOV 31H, #20

INC 30H

MOV A, 30H ; copy the count in ACC

CJNE A, #11, NO_CLR ; check if count > 10

MOV 30H, #0 ; clear the count

CLR A

NO_CLR:

CPL A ; because LEDs are active low.

MOV P1, A ; display count on LEDs

SJMP BACK

END

;****************************************************

7.6 Procedure

1. Create a folder “8051” in D:\ and open it. If it already exists, open it.2. Copy the folder “07 Timer0 as Timer” from the “8051 Programs” folder in the CD, to

D:\8051.

MikroDes Systems (www.mikrodes.com)

Page 40: MD51 Lab Manual

MikroDesSystems

38 Study of Timer0 in timer mode

3. Open the folder D:\8051\07 Timer0 as Timer. Double click to open the Vision project“Timer0 as Timer.uvproj”. The project will open in the Vision software.

4. Build the project. This will create the .hex file in the project folder. Verify that it iscreated.

5. Follow the instructions given in appendix A on page 77, and download the .hex file inthe micro-controller.

6. Observe that, the LEDs connected to P1 show incrementing binary number.

7.7 ObservationsWrite the observations which you made after downloading the program in MD51 kit.

7.8 ConclusionsWrite conclusion based on your observations.

7.9 HomeworkModify the program to increase the time delay to 2 sec.

MikroDes Systems (www.mikrodes.com)

Page 41: MD51 Lab Manual

MikroDesSystems

Experiment 8

Study of Timer0 in counter mode

8.1 ObjectivesThe objectives of this experiment are,

1. To understand Timer in 80512. To create time delay using timer3. To display incrementing number on LEDs

8.2 Prerequisites1. Understanding of 8051 architecture2. MOV, CPL, SJMP instructions3. Experiments 1 to 4 should have been performed

8.3 Apparatus1. PC with Windows XP and Keil uVision installed.2. 8051/89V51RD2 data sheet3. MD51 educational trainer kit, serial cable, jumper wire and power adapter

8.4 TheoryIn the experiment on timer as Timer, we studied that when the timer is working with internalclock then it is said to work in Timer mode and when the timer is used with external clock, itis said to be in counter mode. This mode is useful to count number of external events; hencethe counter mode can be used to implement event counter.

In this experiment, we are going to configure the timer0 as Counter in mode 1. In thismode, we will count the external events (such as key press) and the count of number of eventsoccurred will be shown on port P1.

8.4.1 Activity 1

Draw the block diagram of timer0 in mode 1, in figure 8.1 in your notebook.From the block diagram, we can understand that, to use the timer0 as Counter in mode 1,

we have to SET the C/T̄ bit. Then we have to clear GATE bit. Also we have to set the TR0bit. After this we must provide the external clock (pulses) on T0 pin. (P3.4).

In MD51 kit, we can easily verify the counter operation, by using the push button switchesplaced in right bottom corner. These are named as INT0 and INT1; however they can bealso used for giving pulses to timer input. For this, you need to connect the INT0 pin on theconnector to P3.4 on the 10 pin box header (on the left side of the kit.). After this connection,if we press the INT0 key, then P3.4 will go low and if we release the INT0 key, P3.4 will gohigh. You can verify this by connecting logic probe to P3.4. Thus, the INT0 key can be usedto provide the pulses (clock) to the timer (used as counter).

Page 42: MD51 Lab Manual

MikroDes

Systems

40 Study of Timer0 in counter mode

Figure 8.1: Timer0 block diagram

8.4.2 Activity 2

Read the program, comments and understand the program given in section 8.5.

8.5 Program;****************************************

; THIS PROGRAM DEMONSTRATES TIMER USED AS

; COUNTER: Tested on MD51 V1.0 kit

; input: Key press (S1)(INT0)

; output: count on LEDs

; Procedure:

; Disconnect the DS8 dip switch and

; connect the pin 1 (int0) of X11 to P3.4

; on the box header. Then press S1 (int0 SWITCH) and

; observe LEDs

; IMP: Due to switch-bouncing, there may be

; multiple increments. You can remove bouncing (de-bounce)

; with an external 33uF capacitor between

; P3.4 and GND (Use SIP connector near box

; type connector and use the jumpers provided).

; Copyright (c) Aug 2009

; MikroDes Systems, Sangli

;****************************************

ORG 0000

SJMP START

START:

MOV P1, #0FFH; ALL LEDs OFF

; Timer 0 set in mode 1

; and works as counter

MOV TMOD, #05; 0000 0110

MOV TL0, #0

MOV TH0, #0

MikroDes Systems (www.mikrodes.com)

Page 43: MD51 Lab Manual

MikroDesSystems

Sect. 8.6 Procedure 41

SETB TR0

BACK:

MOV A, TL0 ; Complement it

CPL A ; because LEDs are active low.

MOV P1, A ; copy timer value to port

SJMP BACK

END

;****************************************

8.6 Procedure1. Create a folder “8051” in D:\ and open it. If it already exists, open it.2. Copy the folder “07 Timer0 as counter” from the “8051 Programs” folder in the CD, to

D:\8051.3. Open the folder D:\8051\07 Timer0 as counter. Double click to open the Vision project

“Timer0 as counter.uvproj”. The project will open in the Vision software.4. Build the project. This will create the .hex file in the project folder. Verify that it is

created.5. Connect the INT0 pin on the connector X11 (near INT0 key in the right bottom corner

of the kit) to P3.4 on the 10 pin box header (on the left side of the kit.). After thisconnection, if we press the INT0 key, then P3.4 will go low and if we release the INT0key, P3.4 will go high. You can verify this by connecting logic probe to P3.4.

6. Follow the instructions given in appendix A on page 77, and download the .hex file inthe micro-controller.

7. You will observe that all the LEDs are off. This is because, the counter value is 00000000.Now press the key (INT0) near the right bottom corner of the kit, to give pulse input tothe counter. Release the key. Observe that, the LEDs connected to P1 show 00000001.Go on pressing the key multiple times. You will observe that, incrementing binarynumber. The binary number on LEDs will increment after each key press.

8.7 ObservationsWrite the observations which you made after downloading the program in MD51 kit.

8.8 ConclusionsWrite conclusion based on your observations.

8.9 HomeworkConnect the pin P3.4 to output of 555 timer on the board. Observe the output. You willfind that the count on LEDs changes very fast. Find the reason for it. Change the programsuitably to see the incrementing count on LEDs.

MikroDes Systems (www.mikrodes.com)

Page 44: MD51 Lab Manual

MikroDesSystems

42 Study of Timer0 in counter mode

MikroDes Systems (www.mikrodes.com)

Page 45: MD51 Lab Manual

MikroDesSystems

Experiment 9

Study of LCD display

9.1 Aim1. To study the connections of LCD module2. To study the commands to control LCD module3. writing a program to Display a string on LCD display

9.2 TheoryLCD (Liquid Crystal Display ) modules are very popular because of the follwing advantages.

1. Low cost2. Can display alphanumeric text3. It has built in display controller4. Available with 1, 2, 4, lines and 16, 20, 40 characters in a line

The MD51 kit has a on-board LCD module. This allows us to display alphanumeric characterssuch as numbers, text messages etc. The block diagram of it is shown on figure 9.1.

An LCD module has a display as well as display controller IC. This IC needs to be givencertain commands to use the display. The controller also has its own display RAM. The useris expected to write into this RAM. The rest of the functions are done by the controller ICto take the RAM data and display it on LCD. The LCD controller also supports variouscommands such as Clear Display, Blink Cursor, Move Cursor etc. There are various types ofLCD modules.

Figure 9.1: LCD block diagram

9.3 ActivitySurf the Internet to get links to tutorials on LCD modules. Follow those links to know moreabout them. Prepare a note on LCD modules available in market.

9.4 LCD pinsThe LCD module available on MD51 kit is a of 16x2 type. (i.e.), it can display 16 characterson each of the 2 lines. The display has total 14 pins for various signals and two pins(Anode-Cathode) for the backlit LEDs. The pin description and connections of LCD are shown infigure 9.2.

Page 46: MD51 Lab Manual

MikroDesSystems

44 Study of LCD display

Figure 9.2: LCD pin functions

9.5 Circuit diagramThe circuit is shown in figure 9.3. Pin 1 of LCD is connected to ground. Pin 2 is connectedto a potentiometer (R28) that is used as contrast control of the LCD. Pin 3 is VCC. Pin 4 isused for deciding if the information sent to display is the data for display or a command issent for display control.

03-Sep-2009 12:57:14 PM f=0.70 D:\mikrodes\projects\mikrodes\8051-trainerkit\8051 md51 kit\8051-Card.sch (Sheet: 2/3)

RS-232

I2C EEPROM I2C RTC

16x2 LCD

4x6 Matrix keypadInterrupt i/p

Relay i/f

8-Bit I2C A/D and D/A converter

Demo

8051-TXD TP

8051-RXD TP

I2C-SCL I2C-SDA

Relay-0

Relay-1

GND TP

DTR

ISP Switch

LCD

DIS

PLAY

16x

2

12

ON

12

ON

12

ON

12

ON

12

34

56

ON

12

34

56

ON

12

34

ON

162738495

X4 G1

G2

GND1

VCC2

CONTR3

RS4

R/W5

E6

D07

D18

D29

D310

D411

D512

D613

D714

A15

K16

DIS

1

R31

12 3

4SW03

12 3

4SW02

12 3

4SW01

12 3

4SW00

12 3

4SW13

12 3

4SW12

12 3

4SW11

12 3

4SW10

12 3

4SW23

12 3

4SW22

12 3

4SW21

12 3

4SW20

12 3

4SW33

12 3

4SW32

12 3

4SW31

12 3

4SW30

12 3

4SW43

12 3

4SW42

12 3

4SW41

12 3

4SW40

12 3

4SW53

12 3

4SW52

12 3

4SW51

12 3

4SW50

R40

R41

R42

R43

C3

C4

C2

C5

R3

SCL6

SDA5

VCC8

GND4

A0 1

A1 2

NC 3

WP 7

U3

C1

SCL6

SDA5

VCC8

GND4

X1 1

X2 2

SQW/NINTB 7

VBAT 3

U5

C9

C14

R17

R8

Q3

C15

C16

R33

R34

R36

R37

R38

R39

R49

R52

12 3

4S3

12 3

4S4

21

K1OS

P

K1

1 X21

2 X22

3 X23

Q1R10

R11

D12

21

K2OS

P

K2

1 X31

2 X32

3 X33

Q2R13

R14

D13

L3

AE

S

R28

X7-1

X7-2

X7-3

X7-4

C13

L1AIN0 1

AIN1 2

AIN2 3

AIN3 4

AOUT 15

VCC

16G

ND

8

A05

A16

A27

AGN

D13

SCL10

SDA9

VREF

14

EXT12

U4

OSC11

C10

341

2

DS1

341

2

DS8

341

2

DS2

341

2

DS3

7891011121

23456

DS5

7891011121

23456

DS6

56781

234

DS7

D19

D17

D11

D9

R20

R16

R7

R6

1 X812 X823 X834 X84

5 X85

1 X612 X62

R5

1 2 3

JP1

X11-1X11-2X11-3X11-4

TP1

TP2

TP3

TP4

R51

D31

R50

D30

R12

D15

R15

D14

C1+1

C1-3

C2+4

C2-5

T1IN11

T2IN10

R1OUT12

R2OUT9

V+ 2

V- 6

T1OUT 14

T2OUT 7

R1IN 13

R2IN 8

U1

GND 15

VCC 16

TP6

X5-1

X5-2

X5-3

X5-4

AE

S

R9

R2

R1

D1

D2

13579

1113

246

1214

810

J3

TP14

Q7

R53

R54

R55

D32

21

3

PGM1

54

6

PGM1

P2.[0..7]

P2.[0..7]

P0.[0..7]

P0.[0..7]

P3.[0..7]

RXD

TXD

P0.0P0.1P2.4P2.5P2.6P2.7

P0.2

P0.7P0.6P0.5P0.4P0.3

P3.1P3.0

P3.2P3.3

P3.6P3.7

P3.4P3.5

LCD-EN

LCD-EN

LCD-D4

LCD-D4

LCD-D5

LCD-D5

LCD-D6

LCD-D6

LCD-D7

LCD-D7LCD-RS

LCD-RS

LCD-CNT

LCD-CNT

P2.0P2.1P2.2P2.3

DTR-TTL

DTR-TTLNPSEN

RST

DB9 FEMALE, H

DGND

+5V

TUX

GR

_16X

2_R

2

DGND

+5V

10E, 1/2Watt

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

SNAP-KEY

47E, 1/4Watt

47E, 1/4Watt

47E, 1/4Watt

47E, 1/4Watt

1uF, 25V, Tantalum

1uF, 25V, Tantalum

1uF, 25V, Tantalum

1uF, 25V, Tantalum

47E, 1/4Watt

AT24C512-DIP8

0.1u

F, C

eram

ic

DS1307-DIP8

0.1u

F, C

eram

ic

0.1u

F, C

eram

ic

DGND DGND

+5V +5V

4.7K

, 1/4

Wat

t

4.7K

, 1/4

Wat

t

32.7

68K

Hz,

H

10pF, Ceramic

10pF, Ceramic+VBAT

47E, 1/4Watt

47E, 1/4Watt

47E, 1/4Watt

47E, 1/4Watt

47E, 1/4Watt

47E, 1/4Watt

DGND

47E, 1/4Watt

47E, 1/4Watt

SNAP-KEY SNAP-KEY

5VDC, TH

+5V

MKDSN3

MKDSN3

MKDSN3

BC5574.7K

, 1/4

Wat

t4.

7K, 1

/4W

att

1N40

07, T

H

5VDC, TH

+5V

MKDSN3

MKDSN3

MKDSN3

BC5574.7K

, 1/4

Wat

t4.

7K, 1

/4W

att

1N40

07, T

H

10uH, 1ADGND

10K,

Pot

4-PIN RELIMATE

DGND

0.1u

F, C

eram

ic

10uH

, 1A

PCF8591P-SOCKED16

+5V

DGNDDGND

1uF,

25V

, Tan

talu

m

DGND

2-POS DIP Switch

2-POS DIP Switch

2-POS DIP Switch

2-POS DIP Switch 6-POS DIP Switch

6-POS DIP Switch

4-POS DIP Switch

5.1V

, ZEN

ER

5.1V

, ZEN

ER

5.1V

, ZEN

ER

5.1V

, ZEN

ER

47E,

1/4

Wat

t

47E,

1/4

Wat

t

47E,

1/4

Wat

t

47E,

1/4

Wat

t MKDSN5-5.08MKDSN5-5.08MKDSN5-5.08MKDSN5-5.08

MKDSN5-5.08

MKDSN2-5.08MKDSN2-5.08

47E, 1/4Watt3-Pi

n Be

rg

4-P

IN R

ELI

MAT

E

+5V

470E, 1/4WattYELLOW, 3mm

470E, 1/4WattYELLOW, 3mm

470E, 1/4Watt

YELLOW, 3mm

470E, 1/4Watt

YELLOW, 3mm

MAX232SOCKED16

+5V

4-PIN RELIMATE

DGND

10K,

Pot

470E

, 1/4

Wat

t

470E

, 1/4

Wat

tYE

LLO

W, 3

mm

YELL

OW

, 3m

m

+5V

DGND

+5V

14-PIN-FRC-M-V

DGND

+5V

BC557

10K,

1/4

Wat

t10K

, 1/4

Wat

t

+5V

DGND

470E

, 1/4

Wat

tR

ED

, 3m

m

SPDT SWITCH

Figure 9.3: LCD connections

Pin 5 is used as RD/WR. When this pin is low, data/command can be written into theLCD module. This pin is grounded. So the LCD is always in write mode. Pin 6 is used toenable the data read/write operation. Pin 7 upto 10 are not connected. This is because, 4bit interfacing mode is used. In this mode, only 4 data line are required. While sending 8bit data, it is sent as two nibbles, one after the other. Pin 11 to 14 are connected to P2.4to P2.7 pins. Pin 15 is connected to VCC and pin 16 is connected to ground through a 10ohm resistor. (The gound is indicated by DGND (digital ground), but can be considered asconventional ground.)

The 6 way DIP switch (DS5) is used to isolate / disconnect the LCD signal lines from theport lines. This enables to use these port lines for some other purpose if required. However,

MikroDes Systems (www.mikrodes.com)

Page 47: MD51 Lab Manual

MikroDesSystems

Sect. 9.6 Flowchart 45

for this experiment, Keep all the switches in DIP switch in ON position. This is important asotherwise the on-board LCD will not work.

9.6 FlowchartFollowing are the various flowcharts which we need to study.

1. Subroutine for LCD command write2. Subroutine for LCD initialization3. Subroutine for LCD data write4. Main program5. Subroutines for various delays

9.6.1 LCD command write

To use an LCD module, we need to write some commands into LCD module in a particularsequence. The list of commands is shown in figure 9.4. For writing any command we have tofollow the steps shown in figure 9.5-(a).

To write command in the LCD module, we need to set the R/S line to low state. Thenoutput lower nibble of the command byte onto P2.7...P2.4. After this make the EN line highand then low, thus producing a pulse. Then output upper nibble of the command byte ontoP2.7...P2.4. After this make the EN line high and then low. This makes the LCD to acceptthe command. Wait for typically 5 mS for the LCD to execute the command.

9.6.2 LCD Data write

For displaying any alphanumeric character, we need to send the ASCII code of the characterto the LCD module as data. For writing data we have to follow the steps shown in figure9.5-(b).

To write data in the LCD module, we need to set the R/S line to High state. Then outputlower nibble of the data byte onto P2.7...P2.4. After this make the EN line high and then low,thus producing a pulse. Then output upper nibble of the data byte onto P2.7...P2.4. After thismake the EN line high and then low. This makes the LCD to accept the data and display itat the current cursor position. Wait for typically 5 mS for the LCD to execute the command.If the data is to be displayed at a particular position, then we need to set the address by usingappropriate command and then write the data.

9.6.3 Initialize LCD module

To use an LCD module, we need to write some commands into LCD module in a particularsequence. The commands will configure the LCD. The flowchart is shown in figure 9.5-(c).

The flowchart shows that, after power on the LCD needs to be given some time to setupinternal circuit. This requires typically 15 mS. So we have to provide delay of 15 mS. Afterthis we have to set the interface length. The interface length can be 8-bit or 4-bit. MD51 uses4-bit interface length, 2 lines, and character font of 5x7 pixels. Therefore, the command byteis 28H.

After this we need to set the cursor direction and no display shift. The command for thisis 06H. Then we need to set cursor move or display shift. The command for the same is 14H.After it, we need to make the display on and hide the cursor. This is done with command byte0CH. At the end, the display needs to be cleared by giving the command 01H. This completesthe initialization of LCD module. Now the LCD is ready to accept the data to be displayed.

MikroDes Systems (www.mikrodes.com)

Page 48: MD51 Lab Manual

MikroDes

Systems

46 Study of LCD display

Code

InstructionRSR/WDB7DB6DB5DB4DB3DB2DB1DB0

DescriptionExecution

time**

Clear display 0 0 0 0 0 0 0 0 0 1Clears display and returns cursor tothe home position (address 0).

1.64mS

Cursor home 0 0 0 0 0 0 0 0 1 *

Returns cursor to home position(address 0). Also returns displaybeing shifted to the original position.DDRAM contents remainsunchanged.

1.64mS

Entry mode set 0 0 0 0 0 0 0 1 I/D S

Sets cursor move direction (I/D),specifies to shift the display (S).These operations are performedduring data read/write.

40uS

Display On/Offcontrol

0 0 0 0 0 0 1 D C BSets On/Off of all display (D), cursorOn/Off (C) and blink of cursor positioncharacter (B).

40uS

Cursor/displayshift

0 0 0 0 0 1 S/C R/L * *Sets cursor-move or display-shift(S/C), shift direction (R/L). DDRAMcontents remains unchanged.

40uS

Function set 0 0 0 0 1 DL N F * *Sets interface data length (DL),number of display line (N) andcharacter font(F).

40uS

Set CGRAMaddress

0 0 0 1 CGRAM addressSets the CGRAM address. CGRAMdata is sent and received after thissetting.

40uS

Set DDRAMaddress

0 0 1 DDRAM addressSets the DDRAM address. DDRAMdata is sent and received after thissetting.

40uS

Read busy-flagand address

counter

0 1 BF CGRAM / DDRAM address

Reads Busy-flag (BF) indicatinginternal operation is being performedand reads CGRAM or DDRAMaddress counter contents (dependingon previous instruction).

0uS

Write to CGRAMor DDRAM

1 0 write dataWrites data to CGRAM or DDRAM. 40uS

Read fromCGRAM or

DDRAM

1 1 read data

Reads data from CGRAM or DDRAM. 40uS

Bit name Setting / Status

I/D 0 = Decrement cursor position 1 = Increment cursor position

S 0 = No display shift 1 = Display shift

D 0 = Display off 1 = Display on

C 0 = Cursor off 1 = Cursor on

B 0 = Cursor blink off 1 = Cursor blink on

S/C 0 = Move cursor 1 = Shift display

R/L 0 = Shift left 1 = Shift right

DL 0 = 4-bit interface 1 = 8-bit interface

N 0 = 1/8 or 1/11 Duty (1 line) 1 = 1/16 Duty (2 lines)

F 0 = 5x7 dots 1 = 5x10 dots

BF 0 = Can accept instruction 1 = Internal operation in progress

Remarks:- DDRAM = Display Data RAM.- CGRAM = Character Generator RAM.- DDRAM address corresponds to cursor position.- * = Don't care.- ** = Based on Fosc = 250kHz.

Figure 9.4: LCD commands

9.6.4 Main program

The flowchart of main program is shown in figure 9.5-(d).Here, first LCD intialize subroutine is called. Then the accumulator is loaded with the

ASCII code of any character. Then the subroutine LCD data write is called. This displaysthe character on the display. We have to repeat the same for other characters in the string wewant to display. The program waits for 1 sec. After it, it clears the display and waits againfor 1 sec. This is repeated to create flashing display.

9.7 Program;*****************************************

; LCD display program for 8051

; Tested with MD51 kit

MikroDes Systems (www.mikrodes.com)

Page 49: MD51 Lab Manual

MikroDes

Systems

Sect. 9.7 Program 47

Start

Initialize LCD

Send text to LCD

Start

Set Command Mode

Place upper nibbleof command on

D7..D4

Stop

Make EN linehigh and then low

Place lower nibbleof command on

D7..D4

Make EN linehigh and then low

Start

Set Data Mode

Place upper nibbleof command on

D7..D4

Make EN linehigh and then low

Place lower nibbleof command on

D7..D4

Make EN linehigh and then low

Start

Wait for 15 mS

Stop

Setinterface data length (DL)=4 bit ,

number of display line (N)=2and character font(F)=5x7 dots.

Wait for 5 mS

Stop

Wait for 1 mS

SetCursor move direction (I/D)

= Auto-increment,Shift the display (S) = No.

SetCursor move, No display shift

Shift direction (R/L)=Right.

Clear display andreturn cursor to the

home position

Set Display ONCursor off

Cursor blinking off

(a) (b) (c) (d)

Wait for 1 sec

Clear LCD

Wait for 1 sec

Figure 9.5: LCD Flowchart

; Copyright (c)

; MikroDes Systems

; http://www.mikrodes.com

; Aug 2009

;*****************************************

RS EQU P0.0

EN EQU P0.1

; ORG is an assemble directive to set the code memory address

ORG 0000H ; starting code address

SJMP START

ORG 0030H

; main program loop

START:

MOV SP, #35H

LCALL LCD_INIT

BACK:

MOV A, #’M’

LCALL LCD_DATA_WRITE

MOV A, #’i’

LCALL LCD_DATA_WRITE

MikroDes Systems (www.mikrodes.com)

Page 50: MD51 Lab Manual

MikroDes

Systems

48 Study of LCD display

MOV A, #’k’

LCALL LCD_DATA_WRITE

MOV A, #’r’

LCALL LCD_DATA_WRITE

MOV A, #’o’

LCALL LCD_DATA_WRITE

MOV A, #’D’

LCALL LCD_DATA_WRITE

MOV A, #’e’

LCALL LCD_DATA_WRITE

MOV A, #’s’

LCALL LCD_DATA_WRITE

MOV A, #’ ’

LCALL LCD_DATA_WRITE

MOV A, #’S’

LCALL LCD_DATA_WRITE

MOV A, #’y’

LCALL LCD_DATA_WRITE

MOV A, #’s’

LCALL LCD_DATA_WRITE

MOV A, #’t’

LCALL LCD_DATA_WRITE

MOV A, #’e’

LCALL LCD_DATA_WRITE

MOV A, #’m’

LCALL LCD_DATA_WRITE

MOV A, #’s’

LCALL LCD_DATA_WRITE

MOV P1, #00H

LCALL DELAY_1_SEC

MOV A, #01H

LCALL LCD_COMMAND_WRITE

MOV P1, #0FFH

LCALL DELAY_1_SEC

SJMP BACK

SJMP $

LCD_INIT:

; WAIL FOR LCD TO SETTLE

LCALL DELAY_5MS

LCALL DELAY_5MS

LCALL DELAY_5MS

MikroDes Systems (www.mikrodes.com)

Page 51: MD51 Lab Manual

MikroDes

Systems

Sect. 9.7 Program 49

LCALL DELAY_5MS

LCALL DELAY_5MS

LCALL DELAY_5MS

;***************************

;IMP: DONOT REMOVE THIS CODE

MOV A, P2

ANL A, #0FH;

MOV P2, A

SETB EN

CLR EN

SETB EN

CLR EN

;***************************

MOV A, #28H

LCALL LCD_COMMAND_WRITE

; FOR SOFTWARE INIT

MOV A, #28H

LCALL LCD_COMMAND_WRITE

MOV A, #28H

LCALL LCD_COMMAND_WRITE

MOV A, #28H

LCALL LCD_COMMAND_WRITE

MOV A, #06H

LCALL LCD_COMMAND_WRITE

MOV A, #14H

LCALL LCD_COMMAND_WRITE

MOV A, #0CH

LCALL LCD_COMMAND_WRITE

MOV A, #01H

LCALL LCD_COMMAND_WRITE

RET

; ********************************

; SUBROUTINE FOR LCD COMMAND WRITE

; INPUT: COMMAND IN ACC

; REGISTERS USED: R0,R1

;*********************************

LCD_COMMAND_WRITE:

; SET THE COMMAND MODE

CLR RS

LCALL LCD_WRITE_BYTE

MikroDes Systems (www.mikrodes.com)

Page 52: MD51 Lab Manual

MikroDes

Systems

50 Study of LCD display

LCALL DELAY_5MS

RET

; ********************************

; SUBROUTINE FOR LCD DATA WRITE

; INPUT: COMMAND IN ACC

; REGISTERS USED: R0,R1

;*********************************

LCD_DATA_WRITE:

; SET THE DATA MODE

SETB RS

LCALL LCD_WRITE_BYTE

LCALL DELAY_5MS

RET

; ********************************

; SUBROUTINE FOR LCD WRITE BYTE

; INPUT: BYTE IN ACC

; REGISTERS USED: R0,R1

; ********************************

LCD_WRITE_BYTE:

; WRITE THE UPPER NIBBLE

; OF ACC TO PORT

; KEEP A COPY OF COMMAND

MOV R0, A

; READ PORT P2

MOV A, P2

; KEEP LOWER NIBBLE AS IT IS

ANL A, #0FH

MOV R1, ACC

; GET THE COMMAND BACK

MOV A, R0

; KEEP UPPER NIBBLE

ANL A, #0F0H

ORL A, R1

; UPDATE PORT 2

MOV P2, A

; PULSE ON EN LINE

CLR EN

LCALL DELAY_1MS

SETB EN

LCALL DELAY_1MS

CLR EN

MikroDes Systems (www.mikrodes.com)

Page 53: MD51 Lab Manual

MikroDes

Systems

Sect. 9.7 Program 51

LCALL DELAY_1MS

; WRITE THE LOWER NIBBLE

; OF COMMAND TO PORT

; GET THE COMMAND BACK

MOV A, R0

; KEEP LOWER NIBBLE

ANL A, #0FH

; SHIFT TO MOVE LOWER NIBBLE

; TO UPPER NIBBLE POSITION

SWAP A

ORL A, R1

; UPDATE PORT 2

MOV P2, A

; PULSE ON EN LINE

CLR EN

LCALL DELAY_1MS

SETB EN

LCALL DELAY_1MS

CLR EN

LCALL DELAY_1MS

RET

; subroutine for delay

DELAY_1_SEC:

SETB RS0

SETB RS1

MOV R0, #55H

DLY2:

MOV R1, #55H

DLY1:

MOV R2, #55H

DJNZ R2, $

DJNZ R1, DLY1

DJNZ R0, DLY2

CLR RS0

CLR RS0

RET

; subroutine for delay

DELAY_5MS:

SETB RS0

SETB RS1

MOV R1, #10H

MikroDes Systems (www.mikrodes.com)

Page 54: MD51 Lab Manual

MikroDesSystems

52 Study of LCD display

DLY5M1:

MOV R2, #55H

DJNZ R2, $

DJNZ R1, DLY5M1

CLR RS0

CLR RS0

RET

; subroutine for delay

DELAY_1MS:

SETB RS0

SETB RS1

MOV R2, #250

DJNZ R2, $

CLR RS0

CLR RS0

RET

; END is an assemble directive and not an instruction

9.8 Procedure1. Create a folder “8051” in D:\ and open it.2. Copy the folder “LCD Display” from the “Programs” folder in the CD, to D:\ 8051.3. Open the folder D:\ 8051\Relay. Double click to open the µVision project “LCD Dis-

play.uvproj”. The project will open in the µVision software.4. Build the project. This will crate a .hex file with name LCD-Display.hex5. Follow the instructions given in appendix A on page 77, and download the .hex file in

the micro-controller.

9.9 ObservationsIt is observed that the LCD displays the message ”MikroDes Systems” and flashes it continu-ously. The LEDs on port P1 also flash.

9.10 ConclusionThe LCD module can be easily programmed to display the desired alphanumeric text message.

9.11 Home-WorkModify the program to change to string to be displayed. Download the program and verify it.

MikroDes Systems (www.mikrodes.com)

Page 55: MD51 Lab Manual

MikroDesSystems

Experiment 10

Sensing key in matrix keyboard

10.1 ObjectivesThe objectives of this experiment are,

1. to understand the basic operation of matrix keyboard2. to understand programming for sensing a key3. verify the operation experimentally

10.2 Prerequisites1. understanding of 8051 architecture2. experiments 1, 2, 5 should have been performed

10.3 Apparatus1. PC with Windows XP and Keil uVision installed.2. 8051/89V51RD2 data sheet3. MD51 educational trainer kit, serial cable and power adapter

10.4 TheoryA matrix keyboard is a keyboard, in which the keys are arranged in rows and columns. Thematrix keyboard has the advantage that, we can interface larger number of keys to a micro-controller using less number of port pins. For example, to interface 16 keys, we require 4x4matrix, which in turn requires 4+4=8 port lines.

The MD51 kit uses 4x4 key matrix. So, it has 4 columns (scan lines), and 4 rows (returnlines). The rows are connected to P0.4, P0.5, P0.6, P0.7 and columns are connected to P2.0,P2.1, P2.2, P2.3 port lines. This is illustrated in the circuit in figure 10.1. The componentlayout of keyboard section on the MD51 kit is shown in figure 10.2. The bottom left cornerkey is connected to P2.0 and P0.7 and the top right key is connected to P2.3 and P0.4.

10.4.1 Operation

The matrix keyboard operates in the following way:

First, observe that, the return lines are pulled up. This ensures that, the value read by themicro-controller from P2.4 ... P2.7 is FF when no key is pressed.

To sense if any key is pressed or not, the micro-controller has to make each scan line low,then read the return lines, check if the value read is non-FF. If it is non-FF then, it concludesthat, a key is pressed, and finds the key code from the scan and return patterns.

If the value read is FF then micro-controller concludes that no key is pressed and it proceedsto make the next scan line low and repeat the process. In this way, the micro-controller canfind the key code of the pressed key.

Page 56: MD51 Lab Manual

MikroDesSystems

54 Sensing key in matrix keyboard

Figure 10.1: 4x4 Matrix keyboard circuit diagram

Figure 10.2: 4x4 Matrix keyboard Layout

10.5 Procedure

We will have to carry out following three activities.

1. Activity 1: Finding return patterns for a given key press2. Activity 2: Understanding the program3. Activity 3: Downloading the program and verifying the operation

MikroDes Systems (www.mikrodes.com)

Page 57: MD51 Lab Manual

MikroDes

Systems

Sect. 10.6 Program 55

10.5.1 Activity 1:

1. Refer to the circuit given in figure 10.1. Assume that all keys are in released condition.Find out the state of return lines? Write the reason.

2. Assume that, the only P2.0 is made low by the micro-controller. If key 0 is pressed,which return line will be affected? Find the return pattern. In this way, find the scanand return patterns of all keys.

10.5.2 Activity 2:

1. Read the program in the section 10.6 and understand it. Look at the scan pattern placedon the scan lines. Also look at the return patterns that are read. Observe, how only4 bits are isolated. Then look at how the return value is used to select the ASCII keycode.

2. Understand how the key code is generated from the scan and return patterns3. Prepare a flowchart from the program.

10.6 Program;***************************************************

; 4x4 matrix keyboard program

; copyright (c) MikroDes Systems 2010

;***************************************************

; key connections

; columns connected to P0.4,5,6,7 and used as return lines

; rows connected to P2.0,1,2,3 and used as scan lines

; P0.7 P0.6 P0.5 P0.4

; P2.3 C D E F

; P2.2 8 9 A B

; P2.1 4 5 6 7

; P2.0 0 1 2 3

; Download the key_sense.hex and press any key on

; the 4x4 keyboard. The LEDs will show the ASCII code

; of the key pressed.

; For example: if you press key 0

; then the ASCII code of ’0’ (i.e.) 30H => 00110000

; is shown on LEDs. If key ’A’ is pressed then ASCII

; code of ’A’ (i.e.) 41H => 01000001 is shown on LEDs

;***************************************************

ORG 0000

SJMP START

MOV SP, #35H ; Necessary since the call is used

START:

CALL GET_KEY ; read key

CPL A ; complement ACC Since LEDs are connected in common anode

MOV P1, A ; Show the ACC on P1 port

CALL DELAY_20_mSEC ; wait for 20 mSec

MikroDes Systems (www.mikrodes.com)

Page 58: MD51 Lab Manual

MikroDes

Systems

56 Sensing key in matrix keyboard

SJMP START ; continue to loop

;*****************************************************

; Routine to read the key

GET_KEY:

SETB RS1 ; switch bank

MOV R1, #’M’

MOV R2, #’M’

; IF KEY NOT RELEASED, LOOP

GK1:

LCALL CHECK_KEY

CJNE A, #’Z’, GK1

GK2:

LCALL CHECK_KEY

MOV R1, A ; KEEP COPY

CALL DELAY_20_mSEC

LCALL CHECK_KEY

MOV R2, A ; KEEP COPY

; IF KEY 1 AND KEY2 ARE NOT EQUAL, REPEAT

CLR C

SUBB A, R1

JNZ GK2

MOV A, R1

SUBB A, #’Z’; IF KEY IS ’Z’ NO KEY IS PRESSED

JZ GK2

MOV A, R1

CLR RS1 ; restore bank

RET ;RETURN WITH KEY IN ACCUMULATOR

;************************************************************

ROW_PORT EQU P2

COL_PORT EQU P0

CHECK_KEY:

; R0 USED FOR STORING KEY PRESS

; R1 USED AS TEMPARARY VALUE

MOV R0, #’Z’;

; MAKE ONLY UPPER SIX LINES OF COLUMN PORT AS INPUT

MOV A, COL_PORT

ANL A, #03H

MikroDes Systems (www.mikrodes.com)

Page 59: MD51 Lab Manual

MikroDes

Systems

Sect. 10.6 Program 57

ORL A, #0FCH

MOV COL_PORT, A

;*********************************************************

; MAKE ROW 0 LOW AND CHECK COLUMN STATUS

; GROUND THE ROW 0 (P2.7)

CHK_ROW0:

MOV ROW_PORT, #0FEH

; READ COLUMNS AND TAKE ONLY REQUIRED

; BITS

MOV A, COL_PORT

ANL A, #0FCH

NEXT01:

CJNE A, #0ECH, NEXT02

MOV R0, #’3’

SJMP CHK_ROW1

NEXT02:

CJNE A, #0DCH, NEXT03

MOV R0, #’2’

SJMP CHK_ROW1

NEXT03:

CJNE A, #0BCH, NEXT04

MOV R0, #’1’

SJMP CHK_ROW1

NEXT04:

CJNE A, #07CH, NEXT05

MOV R0, #’0’

NEXT05:

SJMP CHK_ROW1

;*********************************************************

; MAKE ROW 1 LOW AND CHECK COLUMN STATUS

; GROUND THE ROW 0 (P2.7)

CHK_ROW1:

MOV ROW_PORT, #0FDH

; READ COLUMNS AND TAKE ONLY REQUIRED

; BITS

MOV A, COL_PORT

ANL A, #0FCH

NEXT11:

CJNE A, #0ECH, NEXT12

MOV R0, #’7’

SJMP CHK_ROW2

NEXT12:

CJNE A, #0DCH, NEXT13

MOV R0, #’6’

MikroDes Systems (www.mikrodes.com)

Page 60: MD51 Lab Manual

MikroDes

Systems

58 Sensing key in matrix keyboard

SJMP CHK_ROW2

NEXT13:

CJNE A, #0BCH, NEXT14

MOV R0, #’5’

SJMP CHK_ROW2

NEXT14:

CJNE A, #07CH, NEXT15

MOV R0, #’4’

NEXT15:

SJMP CHK_ROW2

;*********************************************************

; MAKE ROW 2 LOW AND CHECK COLUMN STATUS

; GROUND THE ROW 0 (P2.7)

CHK_ROW2:

MOV ROW_PORT, #0FBH

; READ COLUMNS AND TAKE ONLY REQUIRED

; BITS

MOV A, COL_PORT

ANL A, #0FCH

NEXT21:

CJNE A, #0ECH, NEXT22

MOV R0, #’F’

SJMP CHK_ROW3

NEXT22:

CJNE A, #0DCH, NEXT23

MOV R0, #’E’

SJMP CHK_ROW3

NEXT23:

CJNE A, #0BCH, NEXT24

MOV R0, #’D’

SJMP CHK_ROW3

NEXT24:

CJNE A, #07CH, NEXT25

MOV R0, #’C’

NEXT25:

SJMP CHK_ROW3

;*********************************************************

; MAKE ROW 3 LOW AND CHECK COLUMN STATUS

; GROUND THE ROW 0 (P2.7)

CHK_ROW3:

MOV ROW_PORT, #0F7H

; READ COLUMNS AND TAKE ONLY REQUIRED

; BITS

MOV A, COL_PORT

MikroDes Systems (www.mikrodes.com)

Page 61: MD51 Lab Manual

MikroDesSystems

Sect. 10.6 Program 59

ANL A, #0FCH

NEXT31:

CJNE A, #0ECH, NEXT32

MOV R0, #’L’

SJMP RET_KEY

NEXT32:

CJNE A, #0DCH, NEXT33

MOV R0, #’K’

SJMP RET_KEY

NEXT33:

CJNE A, #0BCH, NEXT34

MOV R0, #’J’

SJMP RET_KEY

NEXT34:

CJNE A, #07CH, NEXT35

MOV R0, #’I’

NEXT35:

SJMP RET_KEY

RET_KEY:

MOV A, R0

RET

; provides delay of ~1 sec @11.0592MHz

DELAY_20_mSEC:

SETB RS0

MOV R0, #1H

DLY2:

MOV R1, #50H

DLY1:

MOV R2, #55H

DJNZ R2, $

DJNZ R1, DLY1

DJNZ R0, DLY2

CLR RS0

RET

END

;*********************************************************

10.6.1 Activity 3:

1. Create a folder “8051” in D:\ and open it. If it already exists, open it.2. Copy the folder “10 Matrix Key Sensing” from the “8051 Programs” folder in the CD,

to D:\8051.3. Open the folder D:\8051\10 Matrix Key Sensing. Double click to open the Vision project

file, “key sense.uvproj”. The project will open in the uVision software.

MikroDes Systems (www.mikrodes.com)

Page 62: MD51 Lab Manual

MikroDesSystems

60 Sensing key in matrix keyboard

4. Build the project. This will create the .hex file in the project folder. Verify that it iscreated.

5. Follow the instructions given in appendix A on page 77, and download the .hex file inthe micro-controller.

6. Observe that, the when we press the left bottom key, then the LEDs show 00110000(30H). This pattern is the ASCII code of the character ‘0’.

7. Press all keys sequentially and observe the LED pattern. Make a table of key pressedand pattern observed.

10.7 ObservationsWrite the observations which you made, while single stepping the program.

10.8 ConclusionsWrite conclusion about matrix keyboard programming.

10.9 HomeworkModify the program so as to assign different key code to each key starting from ASCII ‘A’ toASCII ‘P’. Verify the operation practically.

MikroDes Systems (www.mikrodes.com)

Page 63: MD51 Lab Manual

MikroDesSystems

Experiment 11

Study of external interrupts

11.1 ObjectivesThe objectives of this experiment are,

1. to understand the interrupt structure2. to understand writing an ISR3. verify the operation experimentally

11.2 Prerequisites1. understanding of basics of interrupt2. experiments 1, 2, 5 should have been performed

11.3 Apparatus1. PC with Windows XP and Keil uVision installed2. 8051/89V51RD2 data sheet3. MD51 educational trainer kit, serial cable and power adapter

11.4 TheoryInterrupt is a mechanism that pauses temporarily the normal program flow, then executes asubroutine (called Interrupt Service Routine, ISR), and then resumes normal program flowas if the main program was not interrupted. The ISR is only executed when a certain event(interrupt) occurs. The event may be one of the timers “overflowing”, receiving a character viathe serial port, transmitting a character via the serial port, or one of two “external interrupt”events. The 8051 may be configured so that when any of these events occur the main programis temporarily suspended and control passed to a special section of code related to the eventthat occurred. Once it is completed, control would be returned to the original program. Theability to interrupt normal program execution when certain events occur makes it much easierand much more efficient to handle certain conditions.

In this experiment, we will study the external interrupt in 8051. There are two externalinterrupts in 8051. They are called as INT0 and INT1. The INT0 is available on P3.2 andINT1 is available on P3.3. These interrupt signals are active low; meaning that, the interruptevent occurs when level on these port lines goes low.

Whenever an interrupt event occurs, the corresponding flag bit is set. Then, the programjumps to an address corresponding to the interrupt. The table 12.1 shows the interrupt sources,the corresponding flags and the vector addresses. If we want to use an interrupt then we needto write its service routine at its vector address.

11.4.1 Interrupt facilities in MD51 kit

In the MD51 kit,

Page 64: MD51 Lab Manual

MikroDesSystems

62 Study of external interrupts

Interrupt Flag bit Vector Address

INT0 IE0 0003HTimer0 TF0 000BHINT1 IE1 0013HSerial TI/RI 001BH

Table 11.1: Interrupt flags and Vectors

1. It is possible to manually provide the interrupt, using push button keys. The connectionsare shown in figure 11.1. These keys are placed in the right bottom corner of the kit.The component layout of interrupt section on the MD51 kit is shown in figure 11.3.

2. It is possible to provide interrupt from an external source. You have to connect the TTLsignal to INT0 or INT1 pins on connector X12. Refer to 11.3.

3. There is an on-board square-wave generator near the interrupt section that can be usedto provide repetitive interrupts if required.

Figure 11.1: External Interrupt circuit in MD51 kit

11.5 ProcedureWe will have to carry out following three activities.

1. Activity 1: Understanding the circuit.2. Activity 2: Understanding the program3. Activity 3: Downloading the program and verifying the operation

MikroDes Systems (www.mikrodes.com)

Page 65: MD51 Lab Manual

MikroDes

Systems

Sect. 11.6 Program 63

Figure 11.2: External Interrupt layout in MD51 kit

Figure 11.3: External Interrupt facility in MD51 kit

11.5.1 Activity 1:

1. Refer to the circuit given in figure 11.1. Find the level on P3.2 pin, if we press the INT0key. What will happen if the DIP switch DS8 is off?

2. Find the value of port data to make all LEDs on. Justify your answer.3. Read the data sheet of 8051. Find the SFRs required for handling interrupts. Find the

address of IE register and the bit address of EX0, EX1, and EA bits.

11.5.2 Activity 2:

1. Read the program in the section 11.6 and understand it. Observe how ISR is written soas to start from the interrupt vector.

2. Understand instructions at the start of ISR. They are for saving the status of the mainprogram. Also observe the last part of ISR. It is used to restore the status of mainprogram.

3. Observe the main program and understand the operation. The main program simplyimplements a counter that is displayed on LCD. This forms the main program.

4. Observe the ISR of INT0. It flashes the LED on P1.0 pin three times and the ISR ends.

11.6 Program;******************************************

; Program to illustrate int0 and int1

; Download the interrupt.hex file in

MikroDes Systems (www.mikrodes.com)

Page 66: MD51 Lab Manual

MikroDes

Systems

64 Study of external interrupts

; the MD51 kit

; Press INT0 or INT1 switch and observe

; that based on the interrupt,

; the program goes to ISR and

; the respective LED flashes and

; then the program returns

; to the main routine.

; copyright (c) MikroDes Systems 2010

;******************************************

ORG 0000H

SJMP START

; interrupt INT0

ORG 0003H

LJMP ISR_INT0

; interrupt TIMER0

ORG 000BH

LJMP ISR_TIMER0

; interrupt INT1

ORG 0013H

LJMP ISR_INT1

; interrupt TIMER1

ORG 001BH

LJMP ISR_TIMER1

; interrupt SERIAL

ORG 0023H

LJMP ISR_SERIAL

; MAIN PROGRAM

;**********************************************

; This is the main program. It is a loop,

; which displays the a text on the lcd display.

; main program uses BANK 0

; subroutins use BANK 1

; ISRs use BANK 2

;**********************************************

ORG 0030H

START:

MOV SP, #50H

SETB EX0

SETB EX1

MikroDes Systems (www.mikrodes.com)

Page 67: MD51 Lab Manual

MikroDes

Systems

Sect. 11.6 Program 65

SETB IT0

SETB IT1

SETB EA

CALL LCD_INIT

CALL CLEAR_LCD

; DISPLAY MESSAGE

MOV DPTR, #MSG

CALL PUTSTRING

; INITIALISE COUNTER TO ASCII 0

MOV R0, #30H ; clear counter

REPEAT:

; MOVE CURSOR TO HOME POSITION

MOV A, #0C0H

CALL LCD_COMMAND_WRITE

; DISPLAY COUNT ON LINE 2

MOV A, R0

; DISPLAY THE COUNT

CALL LCD_DATA_WRITE

CALL DELAY_HALF_SEC

INC R0

; repeat

SJMP REPEAT

; MAIN PROGRAM OVER

;************************************

; ISR

;************************************

ISR_INT0:

; SAVE OLD BANK

PUSH PSW

; CHANGE TO BANK2

SETB RS1

CLR RS0

MOV P1, #0FEH

CALL DELAY_HALF_SEC

MOV P1, #0FFH

CALL DELAY_HALF_SEC

MOV P1, #0FEH

MikroDes Systems (www.mikrodes.com)

Page 68: MD51 Lab Manual

MikroDes

Systems

66 Study of external interrupts

CALL DELAY_HALF_SEC

MOV P1, #0FFH

CALL DELAY_HALF_SEC

MOV P1, #0FEH

CALL DELAY_HALF_SEC

MOV P1, #0FFH

CALL DELAY_HALF_SEC

;RESTORE OLD BANK

POP PSW

;CLR IE0

RETI

ISR_TIMER0:

RETI

ISR_INT1:

; SAVE OLD BANK

PUSH PSW

; CHANGE BANK

SETB RS1

CLR RS0

MOV P1, #7FH

CALL DELAY_HALF_SEC

MOV P1, #0FFH

CALL DELAY_HALF_SEC

MOV P1, #7FH

CALL DELAY_HALF_SEC

MOV P1, #0FFH

CALL DELAY_HALF_SEC

MOV P1, #7FH

CALL DELAY_HALF_SEC

MOV P1, #0FFH

CALL DELAY_HALF_SEC

;RESTORE OLD BANK

;POP PSW

CLR IE1

RETI

ISR_TIMER1:

RETI

MikroDes Systems (www.mikrodes.com)

Page 69: MD51 Lab Manual

MikroDes

Systems

Sect. 11.6 Program 67

ISR_SERIAL:

RETI

;**********************************************

; LCD ROUTINES

RS EQU P0.0

EN EQU P0.1

;**********************************************

CLEAR_LCD:

MOV A, #01

CALL LCD_COMMAND_WRITE

RET

PUTSTRING_LCD:

CLR A

MOVC A,@A+DPTR

JZ PS1

CALL LCD_DATA_WRITE

INC DPTR

SJMP PUTSTRING_LCD

PS1:

RET

LCD_INIT:

; WAIL FOR 15 MS

LCALL DELAY_5MS

LCALL DELAY_5MS

LCALL DELAY_5MS

LCALL DELAY_5MS

LCALL DELAY_5MS

LCALL DELAY_5MS

; SET THE INTERFACE

MOV A, #28H

LCALL LCD_COMMAND_WRITE

; FOR SOFTWARE INIT

MOV A, #28H

LCALL LCD_COMMAND_WRITE

MOV A, #28H

LCALL LCD_COMMAND_WRITE

MOV A, #06H

LCALL LCD_COMMAND_WRITE

MOV A, #14H

LCALL LCD_COMMAND_WRITE

MikroDes Systems (www.mikrodes.com)

Page 70: MD51 Lab Manual

MikroDes

Systems

68 Study of external interrupts

MOV A, #0CH

LCALL LCD_COMMAND_WRITE

MOV A, #01H

LCALL LCD_COMMAND_WRITE

RET

; ********************************

; SUBROUTINE FOR LCD COMMAND WRITE

; INPUT: COMMAND IN ACC

; REGISTERS USED: R0,R1

;*********************************

LCD_COMMAND_WRITE:

; SET THE COMMAND MODE

CLR RS

LCALL LCD_WRITE_BYTE

LCALL DELAY_5MS

RET

; ********************************

; SUBROUTINE FOR LCD COMMAND WRITE

; INPUT: COMMAND IN ACC

; REGISTERS USED: R0,R1

;*********************************

LCD_DATA_WRITE:

; SET THE DATA MODE

SETB RS

LCALL LCD_WRITE_BYTE

LCALL DELAY_1MS

RET

; ********************************

; SUBROUTINE FOR LCD COMMAND WRITE

; INPUT: BYTE IN ACC

; REGISTERS USED: R0,R1

; ********************************

LCD_WRITE_BYTE:

; USE BANK 3 FOR ALL ROUTINES

PUSH ACC

PUSH PSW

SETB RS1

SETB RS0

MikroDes Systems (www.mikrodes.com)

Page 71: MD51 Lab Manual

MikroDes

Systems

Sect. 11.6 Program 69

; WRITE THE UPPER NIBBLE

; OF COMMAND TO PORT

; KEEP A COPY OF COMMAND

MOV R0, A

; READ PORT P2

MOV A, P2

; KEEP LOWER NIBBLE AS IT IS

ANL A, #0FH

MOV R1, ACC

; GET THE COMMAND BACK

MOV A, R0

; KEEP UPPER NIBBLE

ANL A, #0F0H

ORL A, R1

; UPDATE PORT 2

MOV P2, A

; PULSE ON EN LINE

SETB EN

CLR EN

; WRITE THE LOWER NIBBLE

; OF COMMAND TO PORT

; GET THE COMMAND BACK

MOV A, R0

; KEEP LOWER NIBBLE

ANL A, #0FH

; SHIFT TO MOVE LOWER NIBBLE

; TO UPPER NIBBLE POSITION

SWAP A

ORL A, R1

; UPDATE PORT 2

MOV P2, A

; PULSE ON EN LINE

SETB EN

CLR EN

POP PSW

POP ACC

RET

; subroutine for delay

DELAY_HALF_SEC:

; USE BANK 1 FOR ALL ROUTINES

PUSH PSW

MikroDes Systems (www.mikrodes.com)

Page 72: MD51 Lab Manual

MikroDes

Systems

70 Study of external interrupts

CLR RS1

SETB RS0

MOV R1, #20H

DLY2:

MOV R2, #55H

DLY1:

MOV R3, #55H

DJNZ R3, $

DJNZ R2, DLY1

DJNZ R1, DLY2

POP PSW

RET

; subroutine for delay

DELAY_5MS:

PUSH PSW

; USE BANK 1 FOR ALL ROUTINES

CLR RS1

SETB RS0

MOV R1, #25H

DLY5M1:

MOV R2, #55H

DJNZ R2, $

DJNZ R1, DLY5M1

POP PSW

RET

; subroutine for delay

DELAY_1MS:

PUSH PSW

; USE BANK 1 FOR ALL ROUTINES

CLR RS1

SETB RS0

MOV R1, #250

DJNZ R1, $

POP PSW

RET

PUTSTRING:

CLR A

MOVC A,@A+DPTR

PS2:

MikroDes Systems (www.mikrodes.com)

Page 73: MD51 Lab Manual

MikroDesSystems

Sect. 11.7 Observations 71

JZ EXIT

CALL LCD_DATA_WRITE

INC DPTR

SJMP PUTSTRING

EXIT:

RET

MSG: DB "INT0, INT1 DEMO",0x00 ; end the string with null char

END

;*********************************************************

11.6.1 Activity 3:

1. Create a folder “8051” in D:\ and open it. If it already exists, open it.2. Copy the folder “11 HW interrupt” from the “8051 Programs” folder in the CD, to

D:\8051.3. Open the folder D:\8051\11 HW interrupt. Double click to open the Vision project file,

“interrupt.uvproj”. The project will open in the uVision software.4. Build the project. This will create the .hex file in the project folder. Verify that it is

created.5. Follow the instructions given in appendix A on page 77, and download the .hex file in

the micro-controller.6. Observe that, the LCD shows a message “INT0, INT1 Demo” and also shows a incre-

menting count.7. Press INT0 key and observe that the LED0 flashes 3 times. During the period the LED

is flashing, the count on LCD does not increment. This indicates that, during ISR, mainprogram stops its function. The counting on LCD starts back when the ISR ends.

8. Press INT1 key and observe what happens.

11.7 ObservationsWrite the observations which you made, while doing this experiment.

11.8 ConclusionsWrite conclusion about interrupt operation and programming.

11.9 HomeworkModify the program so as to

1. Remove all LCD related code. This will make the program simple and small.2. Keep only interrupt and LED related code. Your program should flash LED0 when the

kit is powered on. When INT0 button is pressed, LED0 should stop flashing and LED1should flash 4 times. After it, LED1 should stop and LED0 should continue flashing.

3. build the project, download the program in the MD51 kit and observe the operation.

MikroDes Systems (www.mikrodes.com)

Page 74: MD51 Lab Manual

MikroDesSystems

72 Study of external interrupts

MikroDes Systems (www.mikrodes.com)

Page 75: MD51 Lab Manual

MikroDesSystems

Experiment 12

Study of timer-0 interrupt

12.1 ObjectivesThe objectives of this experiment are,

1. to understand the timer-0 interrupt2. to understand enabling timer interrupt and writing the timer ISR3. verify the operation experimentally

12.2 Prerequisites1. understanding of basics of interrupt2. experiments 1, 2, 11 should have been performed

12.3 Apparatus1. PC with Windows XP and Keil uVision installed2. 8051/89V51RD2 data sheet3. MD51 educational trainer kit, serial cable and power adapter

12.4 TheoryWe have studied the basics of interrupts in the experiment 11. In this experiment, we willunderstand how to use timer interrupt. Timer interrupt is caused when the timer “overflows.”.In 8051 micro controller, there are two 16 bit timers. They are timer0 and timer1. In thisexperiment, we will use timer0 as 16 bit timer. So, it will overflow when the timer0 countchanges from FFFFH to 0000. This is called the “overflow’ of timer. When it happens, theTF0 flag is set and a signal is sent to interrupt system in 8051. If the timer interrupt isenabled (ET0=1) and also the global interrupt enable bit is set (EA=1), then the programjumps to the timer-0 vector (000BH) refer to table 12.1. At this address, we write the ISR oftimer0. This ISR will get executed every time the timer0 overflows. Thus, we can write theprogram to take any desired action, on every timer0 overflow event (i.e.) timer-0 interrupt. Inthis experiment, we use the timer-0 interrupt to toggle the LEDs connected to P1 at regularinterval.

Interrupt Flag bit Vector Address

INT0 IE0 0003HTimer0 TF0 000BHINT1 IE1 0013HSerial TI/RI 001BH

Table 12.1: Interrupt flags and Vectors

Page 76: MD51 Lab Manual

MikroDes

Systems

74 Study of timer-0 interrupt

12.4.1 Implementing timer-0 interrupt

For implementing timer-0 interrupt, we have to write program that will,

1. Initialize the timer0 such that the timer 0 will overflow after 50mSec(i.e.) 50,000 microSeconds.

2. Since the timers in 8051 are upcounting type, and i time3r mode, 8051 timer takes 1uSper increment (@12MHz crystal), we need to load the timer by FFFFH-50000d.

3. Initialize a variable (say ‘count’) to 20.4. Wait for TF0 flag to get set. After TF0 is fount set, clear it and reload the timer by

its initial value. Increment the variable ‘count’ that will store the number of times thetimer 0 has caused the overflow.

5. If the variable ‘count’ reaches 20, it means, one second has elapsed. (50000 uS x 20 = 1Second). Then reload the ‘count’ variable by 20; toggle the LEDs connected at port P1,and repeat the process.

12.5 ProcedureWe will have to carry out following activities.

1. Activity 1: Understanding the program.2. Activity 2: Downloading the program and verifying the operation

12.5.1 Activity 1:

1. Read the program in the section 12.6 and understand it. Observe how ISR is written soas to start from the interrupt vector.

2. Understand instructions at the start of ISR. They are for saving the status of the mainprogram. Also observe the last part of ISR. It is used to restore the status of mainprogram.

3. Observe the main program and understand the operation. The main program simplyimplements a counter that is displayed on LCD. This forms the main program.

4. Observe the ISR of INT0. It flashes the LED on P1.0 pin three times and the ISR ends.

12.6 Program;;***************************************************

; Timer0 interrupt operation

; copyright (c) MikroDes Systems 2010

;***************************************************

; Download the timer0-interrupt.hex and observe

; that, the LED0 (P1.0) flashes after every second.

; The code of flashing the LED is written in the

; ISR of timer0

;***************************************************

; memory location for storing count

COUNT equ 30H

org 0000h

sjmp start

org 000bh

sjmp isr_timer0

MikroDes Systems (www.mikrodes.com)

Page 77: MD51 Lab Manual

MikroDesSystems

Sect. 12.6 Program 75

org 0030h

start:

clr TR0 ; Its better to stop timer before loading it.

mov TH0, #HIGH(0xFFFF-50000) ; load the higher byte of the initial count

mov TL0, #LOW(0xFFFF-50000) ; load the lower byte of the initial count

mov TMOD, #01 ; mode 0, Gate=0, Timer

setb ET0 ; Enable timer 0 interrupt

setb EA ; Enable global interrupt

mov COUNT, #20 ; load the count variable by 20

setb TR0 ; Start Timer0

; the main program loops here.

; However the timer continues to work.

; When it overflows, the program jumps

; to isr and after isr, it returns here back.

sjmp $

; timer 0 ISR

isr_timer0:

clr TR0 ; stop timer 0

; Timer 0 reloading

mov TH0, #HIGH(0xFFFF-50000) ; load the higher byte of the initial count

mov TL0, #LOW(0xFFFF-50000) ; load the lower byte of the initial count

setb TR0 ; Start Timer0

djnz COUNT, exit_isr

; work to be done in ISR

mov COUNT, #20

; toggle an LED

cpl P1.0

exit_isr:

reti

end

;***************************************************

12.6.1 Activity 2:

1. Create a folder “8051” in D:\ and open it. If it already exists, open it.2. Copy the folder “12 timer0-interrupt” from the “8051 Programs” folder in the CD, to

D:\8051.3. Open the folder D:\8051\12 timer0-interrupt. Double click to open the uVision project

file, “timer0-interrupt.uvproj”. The project will open in the uVision software.4. Build the project. This will create the .hex file in the project folder. Verify that it is

created.

MikroDes Systems (www.mikrodes.com)

Page 78: MD51 Lab Manual

MikroDesSystems

76 Study of timer-0 interrupt

5. Follow the instructions given in appendix A on page 77, and download the .hex file inthe micro-controller.

6. Observe that, the LED connected to P1.0 flashes.

12.7 ObservationsWrite the observations which you made, while doing this experiment.

12.8 ConclusionsWrite conclusion about timer-0 interrupt operation and programming.

12.9 HomeworkModify the program so as to change the flashing rate.

MikroDes Systems (www.mikrodes.com)

Page 79: MD51 Lab Manual

MikroDesSystems

Appendix A

Program Downloading ProcedureThis chapter explains the procedure of downloading the .hex file (user program file) into themicro-controller. Follow the following steps for setting the hardware and software.

A.1 Hardware/software Setup1. Connect the male side of serial cable to serial connector (on right top corner) on MD51

kit and female side of the serial cable to COM1 of PC.2. Connect the jack pin of the power adapter to the power socket (left top corner of kit) on

the kit. Connect the adapter to 230V mains socket. Switch on the power.3. Put the power switch on the kit (near the on-board fuse) in ON position. The green

LED will glow. Now set the Auto ISP Mode switch in AUTO mode. This enablesus, to auto-reset the chip before and after downloading the program, hence there is noneed to reset the kit manually after downloading the program. The micro-controller willautomatically will get reset and user program will start running.

4. Make sure that, the DIP switch DS1 (near the serial connector on the kit) is ON.5. We require FlashMagic software to be installed. For this, Open the

“software\FlashMagic” folder from the MikroDes CD and double click on “Flash-Magic for MD51.exe” file. Follow instructions on the screen and finish the installation.If FlashMagic is already installed, skip this step.

A.2 Program downloading1. Locate the download.fms in the project folder. (If it is not there, then, copy it from any

experiment folder from Mikrodes CD and paste it in your project folder.) This will startFlashMagic with proper settings. Select the required .hex file to be downloaded. Makesure that the hex file to be downloaded is selected. Double click on “download.fms” file.

2. Click on the “Start” button on Flash Magic to start the downloading of the hex file.3. The downloading will start and the progress will be indicated in the status bar. During

the downloading, the Tx and Rx LEDs near the serial connector on the kit will blink.After the downloading is complete, message “Finished” appears in flash magic softwarein the status-bar. The kit is automatically reset and your program starts running.

A.3 FlashMagic SettingsIf you follow the procedure in the section A.2, for downloading the .hex file in the MD51 kit,then you need not have to manually do settings in FlashMagic software. However, sometimes,we want to do all settings ourselves, (or we want students to learn it), then follow the procedurebelow.

Start FlashMagic software and do following settings.

1. Set the COM port to “COM1” (or whatever port you have used)2. Set the baud rate between “2400” to “19200”3. Set the device to “89V51RD2”4. Set the interface to “None(ISP)”5. Select the checkbox, “Erase the blocks used by hex file”

MikroDes Systems (www.mikrodes.com)

Page 80: MD51 Lab Manual

MikroDesSystems

78 Program Downloading Procedure

6. Click the “Browse” button to select the hex file to be downloaded. Refer figure A.1.7. Click on “Options menu and select “advanced options. Click on “hardware config” tab.

Select the check box “Use DTR to control RST” is checked. Click on OK. Refer figureA.2

Figure A.1: Flash Magic Settings

Figure A.2: Flash Magic Advanced Settings

MikroDes Systems (www.mikrodes.com)