0% found this document useful (0 votes)
378 views105 pages

Microprocessor Based System Lab Manual

The document discusses writing assembly language programs using an 8086 emulator. It provides examples of tasks like adding two single-digit numbers input by the user and displaying the result, displaying a 10x10 box of asterisks, and reading and displaying the letters of a name individually on new lines. Assembly language offers a more human-readable representation of machine code instructions and a one-to-one mapping with the underlying machine language. Common assembly instruction types are moves, computations, and control flow instructions.

Uploaded by

Burhan Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
378 views105 pages

Microprocessor Based System Lab Manual

The document discusses writing assembly language programs using an 8086 emulator. It provides examples of tasks like adding two single-digit numbers input by the user and displaying the result, displaying a 10x10 box of asterisks, and reading and displaying the letters of a name individually on new lines. Assembly language offers a more human-readable representation of machine code instructions and a one-to-one mapping with the underlying machine language. Common assembly instruction types are moves, computations, and control flow instructions.

Uploaded by

Burhan Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 105

Experiment No.

01
Basics of microprocessors (8086/8088) and Difference between
microcontrollers and microprocessors

Objectives

 To understand basics of microprocessors.


 To understand the difference between microcontroller and microprocessor.

Theory

Microprocessor is an integrated circuit that contains the entire central processing unit of
a computer on a single chip and is programmed to perform arithmetic and logic functions and
can process the digital data.
The microprocessor contains all, or most of, the central processing unit (CPU)
functions and is the "engine" that goes into motion when you turn your computer on. A
microprocessor is designed to perform arithmetic and logic operations that make use of small
number-holding areas called registers. Typical microprocessor operations include adding,
subtracting, comparing two numbers, and fetching numbers from one area to another. These
operations are the result of a set of instructions that are part of the microprocessor design.
The first microprocessor was introduced in 1970 by Intel (named 4004). It ran at the
speed of 108 KHz. Four years later, Intel created the 8080 running at just over 2 MHz. This
microprocessor was used on the world's firs personal computer, named Altair Modern
microprocessors contain millions of transistors concentrated on small silicon square. Every
transistor can go on or off, thus creating ones and zeros.
Machine Cycle
The steps performed by the computer processor for each machine language instruction
received. The machine cycle is a 4 process cycle that includes reading and interpreting the
machine language, executing the code and then storing that code
.
Types of microprocessors

RISC

The concept was developed by John Cocke of IBM Research during 1974. His
argument was based upon the notion that a computer uses only 20% of the
instructions, making the other 80% superfluous to requirement. A processor
based upon this concept would use few instructions, which would require
fewer transistors, and make them cheaper to manufacture. By reducing the
number of transistors and instructions to only those most frequently used, the
computer would get more done in a shorter amount of time. The term 'RISC'
(short for Reduced Instruction Set Computer) was later coined by David
Patterson, a teacher at the University of California in Berkeley.

1
CISC

CISC (Complex Instruction Set Computer) is a retroactive definition that was


introduced to distinguish the design from RISC microprocessors. In contrast to
RISC, CISC chips have a large amount of different and complex instruction.
The argument for its continued use indicates that the chip designers should
make life easier for the programmer by reducing the amount of instructions
required to program the CPU. Due to the high cost of memory and storage
CISC microprocessors were considered superior due to the requirements for
small, fast code. In an age of dwindling memory hard disk prices, code size
has become a non-issue (MS Windows, hello?). However, CISC-based
systems still cover the vast majority of the consumer desktop market. The
majority of these systems are based upon the x86 architecture or a variant. The
Amiga, Atari, and pre-1994 Macintosh systems also use a CISC
microprocessor.

Difference between the Intel 8086 and the Intel 8088

The 8086 has 16 bit data bus; the 8088 has an 8 bit data bus. The 8086 has a 6 byte
instruction queue, and the 8088 has a 4 byte queue.

The 8088 was the chip used in the first IBM PC; the 8086 wasn't used until later models.
Since they share the exact same instruction set, which is referred to as the "x86 instruction
set" these days, this is often confused.

The 8086/8088 microprocessor is a 16 bit computer, with a 20 bit address bus using a
segmented memory architecture.The execution unit architecture, registers, instructions, etc. in
both is the same.The bus interface unit on the 8086 is 16 bits wide, where on the 8088 it is 8
bits wide.

2
Fig. Internal Architecture of 8086

Microprocessor Emulator 8086

Emu8086 is a Microprocessor Emulator with an integrated 8086 Assembler and Free


Tutorial. Emulator runs programs on a Virtual Machine, it emulates real hardware, such as
screen, memory and input/output devices

3
Conclusion

From this lab we learnt the difference between microcontroller and microprocessor as well as
also studied the basic architecture of Intel 8086 processor. This lab also concentrates on the
introduction of emulator 8086 which is a virtual simulator.

Student’s Comments
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

Lesson Learnt
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

4
Experiment No. 02

How to write a code using Assembly Language in emulator 8086.Verify the


output of the following tasks
 Write an assembly program that reads two decimal digits from user
having a sum less than 10, adds them and displays the result on
output.
 Write an assembly program that displays a 10x10 box of asterisks.
 Write an assembly program that reads first four initials of your
name and then displays each letter in new line.
Objectives

 Learn to write an assembly program that reads two decimal digits from user having a
sum less than 10, adds them and displays the result on output.
 Learn to write an assembly program that displays a 10x10 box of asterisks
 Learn to write an assembly program that reads first four initials of your name and then
displays each letter in new line.

Theory

The purpose of this lab is to know about the assembly language and then writing programs in
assembly language and performing various tasks. Assembly language, commonly referred to
as assembly, is a more human readable form of machine language. Every computer
architecture uses its own assembly language Machine language is the pattern of bits encoding
a processor's operations. Assembly will replace those raw bits with a more readable symbols
call mnemonics.

For example, the following code is a single operation in machine language.

0001110010000110

For practical reasons, a programmer would rather use the equivalent assembly representation
for the previous operation.

ADD R6,R2,R6 ; Add $R2 to $R6

This is a typical line of assembly. The op code ADD instructs the processor to add the
operands R2 and R6, which are the contents of register R2 to register R6, and store the results
in register R6. The ";" indicates that everything after that point is a comment, and is not used
by the system.

Assembly has a one-to-one mapping to machine language. Therefore, each line of assembly
corresponds to an operation that can be completed by the processor. This is not the case with

5
high-level languages. The assembler is responsible for the translation from assembly to
machine language. The reverse operation is completed by the disassembler.

Assembly instructions are very simple, unlike high-level languages. Often they only
accomplish a single operation. Functions that are more complex must be built up out of
smaller ones.

The following are common types of instructions:

Moves

 Set a register to a fixed constant value

 Move data from a memory location to a register (a load) or move data


from a register to a memory location (a store). All data must be fetched
from memory before a computation may be performed. Similarly, results
must be stored in memory after results have been calculated.

 Read and write data from hardware devices and peripherals

Computation

 Add, subtract, multiply, or divide. Typically, the values of two registers are
used as parameters and results are placed in a register

 Perform bitwise operations, taking the conjunction/disjunction (and/or) of


corresponding bits in a pair of registers, or the negation (not) of each bit in a
register

 Compare two values in registers (>, < , >=, or <=)

Control Flow
 Jump to another location in the program and execute instructions there
 Jump (branch) to another location if a certain condition holds
 Jump to another location, but save the location of the next instruction as a
point to return to (a call)

Example

The program written in assembly language looks like this:


MOV AX, 47104
MOV DS, AX
MOV [3998], 36
INT 32

When an assembler reads this sample program, it converts each line of code into one CPU-
level instruction. This program uses two types of instructions, MOV and INT. On Intel

6
processors, the MOV instruction moves data around, while the INT instruction transfers
processor control to the device drivers or operating system

ADVANTAGES OF ASSEMBLY PROGRAMMING

The greatest advantage of assembly programming is raw speed. A diligent programmer


should be able to optimize a piece of code to the minimum number of operations required.
Less waste will be produced by extraneous instructions. However, in most cases, it takes an
in-depth knowledge of the processor's instruction set in order to produce better code than the
compiler writer does. Compilers are written in order to optimize your code as much as
possible, and in general, it is hard to write more efficient code than it.

Low-level programming is simply easier to do with assembly. Some system-dependent tasks


performed by operating systems simply cannot be expressed in high-level languages.
Assembly is often used in writing device drivers, the low level code that is responsible for the
interaction between the operating system and the hardware.

Processors in the embedded space, such as TI's MSP430, have the potential for the greatest
gain in using assembly. These systems have very limited computational resources and
assembly allows the maximum functionality from these processors. However, as technology
is advancing, even the lowest power microcontroller is able to become more powerful for the
same low cost.

Assembly language Instructions


Some of the basic instructions used are as follows:
CMP Instruction
Purpose: To compare the operators.
Syntax: CMP destiny, source
This instruction subtracts the source operator from the destiny operator but without this one
storing the result of the operation, and it only affects the state of the flags.
MOV Instruction
Purpose: Data transfer between memory cells, registers and the accumulator.
Syntax: MOV Destiny, Source
Where Destiny is the place where the data will be moved and Source is the place where the
data is.
PUSH Instruction
Purpose: It places a word on the stack.
Syntax: PUSH source
The PUSH instruction decreases by two the value of SP and then transfers the content of the
source operator to the new resulting address on the recently modified register.
POP Instruction
Purpose: It recovers a piece of information from the stack
Syntax: POP destiny
This instruction transfers the last value stored on the stack to the destiny operator, it then
increases by 2 the SP register. This increase is due to the fact that the stack grows from the

7
highest memory segment address to the lowest, and the stack only works with words, 2 bytes,
so then by increasing by two the SP register, in reality two are being subtracted from the real
size of the stack.
TEST Instruction
Purpose: It logically compares the operators
Syntax: TEST destiny, source
It performs a conjunction, bit by bit, of the operators, but differing from AND, this
instruction does not place the result on the destiny operator, it only has effect on the state of
the flags.
General lay out of writing program in assembly
Title
.model small
.stack size
.data
;variables
.code

LAB ASSIGNMENT

1. Write an assembly program that reads two decimal digits whose sum is less than 10,
adds them and prints the sum in new line.

Code

.MODEL SMALL
.STACK 100H

.DATA
PROMPT_1 DB 'Enter the First digit : $'
PROMPT_2 DB 'Enter the Second digit : $'
PROMPT_3 DB 'Sum of First and Second digit : $'

.CODE
MAIN PROC
MOV AX, @DATA ; initialize DS
MOV DS, AX

LEA DX, PROMPT_1 ; load and display the PROMPT_1


MOV AH, 9
INT 21H
MOV AH, 1 ; read a character\digit
INT 21H
MOV BL, AL ; save First digit in BL in ASCII code
SUB BL, 30H

MOV AH, 2 ; new line


MOV DL, 0DH

8
INT 21H

MOV DL, 0AH


INT 21H

LEA DX, PROMPT_2 ; load and display the PROMPT_2


MOV AH, 9
INT 21H

MOV AH, 1 ; read a character


INT 21H

MOV BH, AL ; save Second digit in BH in ASCII CODE


SUB BH, 30H

MOV AH, 2 ; new line


MOV DL, 0DH
INT 21H

MOV DL, 0AH


INT 21H

LEA DX, PROMPT_3 ; load and display the PROMPT_3


MOV AH, 9
INT 21H

ADD BL, BH ; add First and Second digit


ADD BL, 30H ; convert ASCII to DECIMAL code

MOV AH, 2 ; display the character


MOV DL, BL
INT 21H

MOV AH, 4CH ; return control to DOS


INT 21H
MAIN ENDP
END MAIN

2. Write an assembly program to print a box of 10*10 asterisks.

.MODEL SMALL
.STACK 100H
.DATA
SQUARE DB '**********',0DH,0AH,'$'

.CODE
MAIN PROC
MOV AX, @DATA ; initialize DS
MOV DS, AX

9
LEA DX, SQUARE ; load the string
MOV AH, 9

INT 21H
INT 21H ; display the string 10 times
INT 21H
INT 21H
INT 21H
INT 21H
INT 21H
INT 21H
INT 21H
INT 21H

MOV AH, 4CH ; return control to DOS


INT 21H
MAIN ENDP
END MAIN

3. Write an assembly program that reads the first initials of a person name and display
in four lines

.MODEL SMALL
.STACK 100H

.DATA
PROMPT_1 DB 'Enter four initials : $'
PROMPT_2 DB 0DH,0AH,'The initials are :',0DH,0AH,'$'
NEWLINE DB 0DH,0AH,'$'

.CODE
MAIN PROC
MOV AX, @DATA ; initialize DS
MOV DS, AX

LEA DX, PROMPT_1 ; load and display PROMPT_1


MOV AH, 9
INT 21H

MOV AH, 1 ; read first initial


INT 21H

MOV BL, AL ; save the first initial into BL

MOV AH, 1 ; read second initial


INT 21H

MOV BH, AL ; save the second initial into BH

MOV AH, 1 ; read third initial

10
INT 21H

MOV CL, AL ; save the third initial into CL

MOV AH, 1 ; read fourth initial


INT 21H

MOV CH, AL ; save the fourth initial into CL

LEA DX, PROMPT_2 ; load and display PROMPT_2


MOV AH, 9
INT 21H

MOV AH, 2 ; display the first initial


MOV DL, BL
INT 21H

LEA DX, NEWLINE ; display new line


MOV AH, 9
INT 21H

MOV AH, 2 ; display the second initial


MOV DL, BH
INT 21H

LEA DX, NEWLINE ; display new line


MOV AH, 9
INT 21H

MOV AH, 2 ; display the third initial


MOV DL, CL
INT 21H

LEA DX, NEWLINE ; display new line


MOV AH, 9
INT 21H

MOV AH, 2 ; display the fourth initial


MOV DL, CH
INT 21H

MOV AH, 4CH ; return control to DOS


INT 21H
MAIN ENDP
END MAIN

Conclusion

11
From this lab we learnt about an assembly program that reads two decimal digits from user
having a sum less than 10, adds them and displays the result on output. Learn to write an
assembly program that displays a 10x10 box of asterisks also learn to write an assembly
program that reads first four initials of your name and then displays each letter in new line.

Student’s Comments
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

Lesson Learnt
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

12
Experiment No.03

How to use flow Control Instructions in assembly language.


a) Write an assembly program that reads a key then displays its status
as a digit or as uppercase or lowercase letter or some other key.
b) Write an assembly program that displays a message 50 times using
loop instruction.
c) Write an assembly program that reads two number from user and
then shows which is smaller one
Objectives

 To understand the use of flow control instructions in assembly language


 To analyze data movement in 8086 register using a program applying flow control
instruction

Theory

The purpose of this lab is to study the flow control instructions like jump, loop etc and study
their use in assembly programs. Program/Flow control instructions change or modify the flow
of a program. The most basic kind of program control are:
 Conditional
 Unconditional

Unconditional jump
This is performed by the JMP instruction. Conditional execution often involves a transfer of
control to the address of an instruction that does not follow the currently executing
instruction. Transfer of control may be forward, to execute a new set of instructions or
backward, to re-execute the same steps.

Unconditional jump

This is performed by the JMP instruction. Conditional execution often involves a transfer of
control to the address of an instruction that does not follow the currently executing
instruction. Transfer of control may be forward, to execute a new set of instructions or
backward, to re-execute the same steps.
There are numerous conditional jump instructions depending upon the condition and data.
Following are the examples of some conditional jump instructions.

Instruction Description Flags tested

13
JE/JZ Jump Equal or Jump Zero ZF
JNE/JNZ Jump not Equal or Jump Not Zero ZF
JA/JNBE Jump Above or Jump Not Below/Equal CF, ZF
JAE/JNB Jump Above/Equal or Jump Not Below CF
JB/JNAE Jump Below or Jump Not Above/Equal CF
JBE/JNA Jump Below/Equal or Jump Not Above AF, CF

The following conditional jump instructions have special uses and check the value of flags −

Instruction Description Flags tested


JXCZ Jump if CX is Zero none
JC Jump If Carry CF
JNC Jump If No Carry CF
JO Jump If Overflow OF
JNO Jump If No Overflow OF
JP/JPE Jump Parity or Jump Parity Even PF
JNP/JPO Jump No Parity or Jump Parity Odd PF
JS Jump Sign (negative value) SF
JNS Jump No Sign (positive value) SF

Let us discuss the CMP instruction before discussing the conditional instructions.

CMP Instruction
The CMP instruction compares two operands. It is generally used in conditional execution.
This instruction basically subtracts one operand from the other for comparing whether the
operands are equal or not. It does not disturb the destination or source operands. It is used
along with the conditional jump instruction for decision making.

Syntax
CMP destination, source
CMP compares two numeric data fields. The destination operand could be either in register or
in memory. The source operand could be a constant (immediate) data, register or memory.

Example
ADD
AGAIN: MOV
SUB
INC
DEC
JUMP AGAIN

Example of conditional jump

MOV CX,8 ;it will run 8 times


AGAIN:
ADD CX
14
SUB CX
DEC CX
JNZ AGAIN ;jump if not zero

LAB TASK

1. Write an assembly program that reads a character and alphabets and displays the
status of the pressed key i.e. small, capital, number etc.

Code

. .MODEL SMALL
.STACK 100H

.DATA
MSG DB 'please enter your desired key: $'
MSG1 DB 0DH,0AH,'you have entered a capital letter ','$'
MSG2 DB 0DH,0AH,'you have entered a small letter ','$'
MSG3 DB 0DH,0AH,'you have entered a digit ','$'
MSG4 DB 0DH,0AH,'you have entered some character other than alphabets and digits
','$'

.CODE
MAIN PROC ; initialize DS
MOV AX,@DATA
MOV DS,AX

LEA DX,MSG ; load and print MSG


MOV AH,9
INT 21H

MOV AH,1 ; read a letter


INT 21H
MOV BL,AL

MOV DL,29H

CMP BL,39H ;compare DL and 39H


JG _UCASE
_DIGITS:
INC DL
CMP BL,DL ;compare DL and BL
JL _disp_other_char
JZ _disp_dig
JG _DIGITS

_UCASE:
MOV DL,40H

15
_UPPER_CASE:
CMP BL,5AH ;compare DL and 5AH
JG _LCASE
INC DL
CMP BL,DL
JZ _disp_ucase
JG _UPPER_CASE

_LCASE:

MOV DL,60H

_LOWER_CASE:
CMP BL,7AH ;compare DL and 7AH
JZ _disp_other_char
INC DL
CMP BL,DL
JZ _disp_lcase
JG _LOWER_CASE

_disp_ucase:
LEA DX,MSG1 ; load and print MSG1
MOV AH,9
INT 21H
JMP ENDD ;jump to label ENDD

_disp_lcase:
LEA DX,MSG2 ; load and print MSG2
MOV AH,9
INT 21H
JMP ENDD ;jump to label ENDD

_disp_dig:
LEA DX,MSG3 ; load and print MSG3
MOV AH,9
INT 21H
JMP ENDD ;jump to label ENDD

_disp_other_char:
LEA DX,MSG4 ; load and print MSG4
MOV AH,9
INT 21H
JMP ENDD ;jump to label ENDD

ENDD:
MOV AH,4CH ; return control to DOS
INT 21H

16
MAIN ENDP
END MAIN
2. Write an assembly program that reads a lower case letter and displays it in the
upper case.

Code
.MODEL SMALL
.STACK 100H
.DATA
MSG1 DB 'Enter the Lower Case Letter : $'
MSG2 DB 'The Upper Case Letter is : $'

.CODE
MAIN PROC
MOV AX, @DATA ; initialize DS
MOV DS, AX

LEA DX, MSG1 ; load and print MSG1


MOV AH, 9
INT 21H

MOV AH, 1 ; read a letter


INT 21H
MOV BL, AL ; save the letter in BL
MOV AH, 2 ; new line
MOV DL, 0DH
INT 21H

MOV DL, 0AH


INT 21H

LEA DX, MSG2 ; load and print MSG22


MOV AH, 9
INT 21H

SUB BL, 20H ; convert a lower case letter to upper case letter

MOV AH, 2 ; print the Upper case letter


MOV DL, BL
INT 21H

MOV AH, 4CH ; return control to DOS


INT 21H
MAIN ENDP
END MAIN

LAB ASSIGNMET

17
Write an assembly program that reads three digits from user and then displays which is
the highest number

Conclusion

From This Lab We Learnt About flow control instructions. This lab also helps to understand
the difference between conditional and unconditional jump instructions in assembly
language. This lab also helps o understand the ascii codes and how to manipulate them.

Student’s Comments
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

Lesson Learnt
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

18
Experiment No. 04
Use of multiplication and division instructions
 Write an assembly program the reads two number (0-99) from user
and divides the first by second. Finally display the results.
 Write an assembly program that reads a number from user and
displays the factorial of the number.
Objectives

 To understand the use of multiplication and division instructions in assembly


language
 To analyze data movement in 8086 registers using a program performing
multiplication and division of different numbers

Theory

The purpose of this lab is to study some basic multiplication and division instructions and
construct various programs using them

MUL Instruction

Purpose: Multiplication with sign.

Syntax: MUL source

The assembler assumes that the multiplicand will be of the same size as the multiplier,
therefore it multiplies the value stored on the register given as operator by the one found to be
contained in AH if the multiplier is 8 bits or by AX if the multiplier is 16 bits. When a
multiplication is done with 8 bit values, the result is stored on the AX register and when the
multiplication is with 16 bit values the result is stored on the even DX:AX register.

IMUL Instruction

Purpose: Multiplication of two whole numbers with sign.

Syntax: IMUL source

This command does the same as the one before, only that this one does take into account the
signs of the numbers being multiplied.

DIV Instruction

Purpose: Division without sign.

19
Syntax: DIV source

The divider can be a byte or a word and it is the operator which is given the instruction. If the
divider is 8 bits, the 16 bits AX register is taken as dividend and if the divider is 16 bits the
even DX:AX register will be taken as dividend, taking the DX high word and AX as the low.
If the divider was a byte then the quotient will be stored on the AL register and the residue on
AH, if it was a word then the quotient is stored on AX and the residue on DX.

IDIV Instruction

Purpose: Division with sign.

Syntax: IDIV source

It basically consists on the same as the DIV instruction, and the only difference is that this
one performs the operation with sign. For its results it used the same registers as the DIV
instruction.

LAB TASK

1. Write a program that will read a positive binary number and print its factorial in
binary form using MUL instruction.

Code

.MODEL SMALL
.STACK 100H

.DATA
PROMPT_1 DB 'Enter a Positive Binary number (max. 1000) : $'
PROMPT_2 DB 0DH,0AH,'The Factorial of the given number is : $'
ILLEGAL DB 0DH,0AH,'Illegal character. Try again : $'

.CODE
MAIN PROC
MOV AX, @DATA ; initialize DS
MOV DS, AX

LEA DX, PROMPT_1 ; load and display the string PROMPT_1


MOV AH, 9
INT 21H

CALL BINARY_INPUT ; call the procedure BINARY_INPUT

CALL FACTORIAL ; call the procedure FACTORIAL

LEA DX, PROMPT_2 ; load and display the string PROMPT_2


MOV AH, 9

20
INT 21H

CALL BINARY_OUTPUT ; call the procedure BINARY_OUTPUT

MOV AH, 4CH ; return control to DOS


INT 21H
MAIN ENDP
BINARY_INPUT PROC
; this procedure will read a number in binary form
; input : none
; output : store binary number in BL
; uses : MAIN

JMP @START ; jump to label @START

@ERROR: ; jump label

LEA DX, ILLEGAL ; load and display the string ILLEGAL


MOV AH, 9
INT 21H

@START: ; jump label

MOV CX, 4 ; initialize loop counter


XOR BX, BX ; clear BX
MOV AH, 1 ; set input function

@INPUT: ; loop label


INT 21H ; read a digit

CMP AL, 0DH ; compare input and CR


JE @END ; jump to label @END if input is CR

CMP AL, 30H ; compare AL with 0


JL @ERROR ; jump to label @ERROR if AL<0

CMP AL, 31H ; compare AL with 1


JG @ERROR ; jump to label @ERROR if AL>1

AND AL, 0FH ; convert ascii to decimal code


SHL BL, 1 ; shift BL by 1 position towards left
OR BL, AL ; place the input decimal digit in BL
LOOP @INPUT ; jump to label @INPUT if CX!=0

@END: ; jump label

RET ; return control to the calling procedure


BINARY_INPUT ENDP
BINARY_OUTPUT PROC
; this procedure will display a number in binary form

21
; input : BX
; output : none
; uses : MAIN

MOV CX, 16 ; initialize loop counter


MOV AH, 2 ; set output function

@OUTPUT: ; loop label


SHL BX, 1 ; shift BX by 1 position towards left
JC @ONE ; jump to label @ONE if CF=1
MOV DL, 30H ; move 0 to DL
JMP @DISPLAY ; jump tp label @DISPLAY

@ONE: ; jump label


MOV DL, 31H ; move 1 to DL

@DISPLAY: ; jump label


INT 21H ; display a digit
LOOP @OUTPUT ; jump to label @OUTPUT if CX!=0

RET ; return control to the calling procedure


BINARY_OUTPUT ENDP

FACTORIAL PROC
; this procedure will computes the factorial of a given number
; input : BL
; output : store the factorial of the number in BX
; uses : MAIN

MOV AX, 1 ; set AX=1

XOR CX, CX ; clear CX


MOV CX, BX ; set CX=BX

@LOOP: ; loop label


MUL CX ; multiply CX with AL i.e. AX=AL*CX
LOOP @LOOP ; jump to label @LOOP if CX!=0

MOV BX, AX ; set BX=AX

RET ; return control to the calling procedure


FACTORIAL ENDP
END MAIN

LAB Assignment

Write an assembly program that takes two numbers (0-99) and then divides the first by
second one, finally display the result.

22
Conclusion

From this lab we learn to write assembly program the reads two number (0-99) from user and
divides the first by second. Also learn assembly program that reads a number from user and
displays the factorial of the number. Hence the student will understand the concept of
multiplication as well as division instructions and data manipulation in 80856 registers.

Student’s Comments
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

Lesson Learnt
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

23
Experiment No. 5

Discuss different families of microcontrollers. Introduction to AVR family.


Pin Configuration of atmega16. Familiarization to Codevision. (Compiler)

Objectives
 To study the different microcontroller families and specially AVR family
 To study pin configuration of atmega16
 To learn the use of Codevision (avr programming tool).

Theory

Microcontroller can be termed as a single on chip computer which includes number of


peripherals like RAM, EEPROM, Timers etc., required to perform some predefined task.
There are number of popular families of microcontrollers which are used in different
applications as per their capability and feasibility to perform the desired task, most common
of these are 8051, AVR and PIC microcontrollers.

History of AVR

AVR was developed in the year 1996 by Atmel Corporation. AVR is also known
as Advanced Virtual RISC.

AVR microcontrollers are available in three categories:

1. Tiny AVR – Less memory, small size, suitable only for simpler applications
2. Mega AVR – These are the most popular ones having good amount of memory higher
number of inbuilt peripherals and suitable for moderate to complex applications.
3. Xmega AVR – Used commercially for complex applications, which require large
program memory and high speed.

What’s special about AVR?

They are fast: AVR microcontroller executes most of the instructions in single execution
cycle. AVR is an 8-bit RISC based microcontroller. 8-bit u-controller means that the
microcontroller is capable of transmitting and receiving 8-bit data. The input/output registers
available are of 8-bits.
In our journey with the AVR we will be working on Atmega16 microcontroller, which is a
40-pin IC and belongs to the mega AVR category of AVR family.
Some of the features of Atmega16 are:

24
 16KB of Flash memory
 1KB of SRAM
 512 Bytes of EEPROM
 Available in 40-Pin DIP
 8-Channel 10-bit ADC
 Two 8-bit Timers/Counters
 One 16-bit Timer/Counter
 4 PWM Channels
 In System Programmer (ISP)
 Serial USART
 SPI Interface
 Digital to Analog Comparator.

25
There are two flavors for Atmega16 microcontroller:
1. Atmega16:- Operating frequency range is 0 – 16 MHz.
2. Atmega16L:- Operating frequency range is 0 – 8 MHz.
Naming Convention
The AT refers to Atmel the manufacturer, Mega means that the microcontroller belong to
MegaAVR category, 16 signifies the memory of the controller, which is 16KB.

Naming Convention of ATmega16 - AVR Family

AVR Registers

A register is a special storage space in which the state of the bits in the register have some
special meaning to the AVR microcontroller. Most of the registers are 8-bits wide (there are a
few exceptions).Each register has a name and individual bits may also have unique names
Manipulating the bits in the various registers is the basis for programming. Everything from
configuring the AVR device's built-in peripherals to using the AVR's pins for digital I/O is done
By manipulating bits in these registers.

Bits and Bytes


A bit represents one of two possible states: 1 or 0 (aka: on/off, set/clear, high/low). Several bits
together represent numerical values in binary, where each bit is one binary digit. An AVR
microcontroller groups 8 bits together to form one byte with the Least Significant Bit (LSB) on
the right. Each bit is numbered, starting from 0, at the LSB.
Consider the decimal number 15 for example. 15 represented in 8-bit binary is 00001111. The 4
least significant bits 0, 1, 2, and 3, are set. Another example, the decimal number 40 is
represented in binary as 00101000. Bits 3 and 5 are set.

Numerical values in a C program for an AVR microcontroller may be defined using a decimal,
hexadecimal, or binary notation depending on the context and the programmer's preference. A
hexadecimal number is defined using the 0x prefix and a binary number is defined using
the 0b prefix.

26
The following C code shows 3 ways in which a variable might be initialized to the decimal value
of 15.
Uint8_t a = 15; /* decimal */
Uint8_t b = 0x0F; /* hexadecimal */
Uint8_t c = 0b00001111; /* binary */
The uint8_t data type is one of the fixed width integer types and defines an 8-bit unsigned integer

CVAVR TUTORIAL (CODE VISION AVR)


This is the software for programming of AVR. This is developed by HP.

This software is very user friendly and it is very easy to make a program in this software. In short
CVAVR is for beginners.

Follow all the steps.

1. Download and open CVAVR. Goto file>new.

2. Select file type Project and click ok.

3. Select your chip type and click ok.

27
4. Now a window opens for including various functions or header files in your program
automatically. First select your controller from chip option.

5. If you used LCD in your project then go to LCD and select LCD port.

28
6. If you want to enable ADC in your code then goto ADC and enble it and select various options
according to you requirement.

7. If you want to enable SPI mode then go to SPI and enable it and select various options
according to your requirement. As it is you can include many other options in your program
given in above window automatically.

8. After including all your requirements go to file>generate, save and exit.

29
9. Now this window opens 3 times save your project at the location you want and typr the file
name like evm in all 3 windows. All 3 file names must be same.

10. Now a project window opens where necessary header files are included automatically. You
also can include any header file you want from the CVAVR library.

11. Declare all the variables above and


scroll down to see while(1) function and
write your code in while(1).

30
12. Click the button as shown in window for building your project.

13. Now a windows open make sure there is no error and no warning.

14. You can find your HEX file in EXE folder.

Conclusion

31
From this lab we understand the basic concept of microcontrollers specifically the atmega16 that
is a member of AVR family. This lab also helps to understand the use of Code vision i.e. the
complier used for the programming of atmega16 (target microcontroller)

Student’s Comments
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

Lesson Learnt
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

32
Experiment No. 6
Fuse bit settings in atmega16. Steps to program micro-controller (atmega16)
using super-pro universal programmer. Implement a simple program to blink
a led at PORTA pin 0.
Objectives

 To understand the fuse bits.


 To study the clock speed.
 To configure the microcontroller.
 To analyze different start up times.

Theory

Updating with the era of technology, the new microcontrollers are coming with lots of inbuilt
peripherals and features. These inbuilt peripherals and features not only reduce the cost of
additional circuits to be used with the controller but also provide an ease to interface additional
devices (such as Modems etc.) directly with the microcontroller.
The new generations of microcontrollers are capable of working on internal as well as on
external clock option. As a beginner when you get a new chip (ATmega16/32) you may
complain that ‘PORTC of the chip is not working!’ or ‘when the reset pin and 6th pin of PORTC
(in ATmega8) are common how shall I select them/distinguish between them? These questions
may taste bitter when you try to skip them and go ahead, but all these issues can be solved by
properly setting the FUSE BITS of your device.
There are only two fuse bytes: a high one, and a low one. As you should hopefully know, one
byte contains 8 bits. So we have 16 bits to set to on or off. Each of those bits, depending on
whether they are on or off, impacts the critical operations of the microcontroller. The mistake
most people make is messing around with bits they did not intend to change, or giving bits they
intended to change the wrong value. This is particularly easy because a bit set to 0 means it is
programmed, and a bit set to 1 means it is UN programmed

What is a clock?
A clock is simply a device that keeps track of time, it kind of gives you a beat to move to. The
clock on your wall counts in increments of seconds. The amount of times a clock ticks/cycles per
second is called its frequency, measured in Hertz (Hz or cycles/second). Similarly, your ATMega
has a clock inside too, and its speed directly relates to how many instructions it can carry out per
second (on every tick/cycle of the clock). The default clock speed that comes shipped with most
AVRs is 1 MHz (1 million cycles per second) because they have internal clocks which keep
time.

33
How can we set a clock speed?
We have two options: use the internal one, or use an external source. If you are writing code that
does basic stuff, and you don’t require precision timing, the internal clock should suffice. In any
other case, particularly for communication (i.e. using the UART for example, or in my case,
USB), timing is critical. In that case, we need an alternate method, so we use things like crystals,
resonators, oscillators, and clocks. They are all suitable to produce the beat we are looking for, at
the frequency we are looking for, but the most common amongst hobbyists are crystals and
resonator (you’ll see how they are pretty much the same). We will be using a crystal for this
tutorial, and it looks like this:

Start-up time
Clocks sources usually need a little bit of time to warm up and start giving us a reliable signal
when the microcontroller is turned on. This is called the start-up time. To play it safe, we will be
using the maximum start-up time to give the clock as much time as it needs to get up to speed
(no pun intended). Actually, the max start-up time is only a few milliseconds anyway!

Description
The AVR microcontroller (ATmega16) consists of sixteen fuse bits which are classified as low
fuse and high fuse. These Fuse bits can be configured to select the microcontroller clock options
or to control some in-built peripherals like JTAG, SPI etc.
A new or virgin microcontroller has a default value of fuse bytes which is equal to 0x99E1 in
hexadecimal. To understand the meaning of this default value, each fuse bit must be understood.

High Fuse bits:

Fuse OCDE JTAGE SPIE CKOP EESAV BOOTSZ BOOTSZ BOOTRS


Bit N N N T E 1 0 T
Bit Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
No.
Defaul 1 0 0 1 1 0 0 1
t
Values

Low Fuse bits:

Fuse BODLEVEL BODEN SUT1 SUT0 CKSEL3 CKSEL2 CKSEL1 CKSEL0


Bit
Bit No. Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Default 1 1 1 0 0 0 0 1
values

34
CKSEL [3:0] (Clock Select)

These fuse bits are used to select different clock source option for microcontroller. The table
Below shows the different device clock sources and their corresponding fuse bits.

Device Clocking Option CKSEL[3:0]


External Crystal/Ceramic Resonator 1111 – 1010
External Low-frequency Crystal 1001
External RC Oscillator 1000 - 0101
Calibrated Internal RC Oscillator 0100 - 0001
External Clock 0000

The default clock setting for new controller is CKSEL = 0001 (internal RC oscillator 1MHz).
Generally, external crystal is used as a clock option (so fuse bit is set between the ranges 1111-
1010).

CKOPT (Clock Option)

There are two oscillation modes in ATmega16 microcontroller; the CKOPT bit selects one of
these modes. If CKOPT bit is programmed (0), the oscillator generates full rail-to-rail output
swing. This mode has wide frequency range. If CKOPT is unprogrammed (1), the oscillation has
smaller output swing (this mode has limited frequency).

Atmega16 can be operated on a maximum clock frequency of 16 MHz (16PU or 16PI), thus the
CKOPT is programmed. The CKOPT bit is combined with CKSEL [3:1] bits to select operating
frequency and its mode. Table2 shows the CKSEL [3:1] and CKOPT bit combination used to
select frequency of crystal for ATmega16. The table below also recommends the capacitors’
ranges which are connected across the crystal.

CKOP CKSEL[3:1] Frequency Range (MHz Recommended Range for


Capacitors (pF)
1 101* 0.4 - 0.9 –
1 110 0.9 - 3.0 12 - 22
1 111 3.0 - 8.0 12 - 22
0 101, 110, 111 1.0 -16.0 12 - 22
* This mode is only used for ceramic resonator.

For CKOPT=0, the CKSEL [3:1] bits are selected as follows:

35
For 12 MHz frequency of external crystal, CKSEL [3:1] is set to 111.

SUT [1:0] (Startup Time)

This bit is used to set start up time of ATmega16. The combination of SUT [1:0] and CKSEL0
bits are used to select the start-up time of controller. The table below shows the bit combinations
to select the start-up time.

CKSEL0 SUT[1:0] No. of Start- Additional Delay Recommended Usage


up clocks from Reset
0 00 258 CK 4.1 ms Ceramic resonator, fast rising power
0 01 258 CK 65 ms Ceramic resonator, slowly rising
power
0 10 1K CK – Ceramic resonator, BOD enabled
0 11 1K CK 4.1 ms Ceramic resonator, fast rising power
1 00 1K CK 65 ms Ceramic resonator, slowly rising
power
1 01 16K CK – Crystal Oscillator, BOD enabled
1 10 16K CK 4.1 ms Crystal Oscillator, fast rising power
1 11 16K CK 65 ms Crystal Oscillator, slowly rising power

BODEN (Brown-Out Detection Enable)

ATmega16 has a brown-out detection unit which continuously monitors Vcc level with fixed
trigger level. This fuse bit is used to enable/disable the brown-out detection unit. To enable the
BOD unit, BODEN bit is programmed (0).

BODLEVEL (Brown-Out Detection Level)

This fuse bit is used to set trigger level for BOD unit. The trigger voltage is set as 2.7 volts, if the
BODLEVEL bit is unprogrammed (1). If this fuse bit is programmed (0), the trigger level is set
to 4.0 volts.

BOOTRST [Bootloader Reset]

Bootloader is a small program which is written on a specific area of the flash memory. This
program executes at the boot time of the controller. If BOOTRST bit is programmed (0), the
device will jump on first address bootloader block.

36
BOOTSZ [1:0]

This fuse bit is used to set the bootloader size. The default value of these bits is ‘00’ which sets
the boot size to 1024 words. This size is allocated from flash memory. Bootloader always resides
at the bottom of flash.

EESAVE (EEPROM Save)

This bit is used to preserve the EEPROM content during chip erase. If the fuse is programmed
(0), the EEPROM preserves its content else it is not preserved during chip erase.

SPIEN (SPI Serial Programming Enable)

If this bit is programmed (0), the SPI serial programming of the controller is enabled. To disable
the serial programming, this bit is left unprogrammed (1).

JTAGEN (JTAG Enable)

There is an in-built JTAG unit in ATmega16, which is pre-activated in virgin microcontroller. To


disable the JTAG, JTAGEN bit should be unprogrammed (1).

OCDEN (On-Chip Debugging Enable)

The on-chip debugging is used to run the program step-by-step on hardware to study the internal
signal which provides the information about state of the processor. This bit is used to

37
enable/disable the on-chip debugging. If this bit is programmed (0), then the on-chip debugging
is enabled.
There are few more bits which are not present in ATmega16 but they are important while using
other ICs of AVR series like ATmega8. The RSTDISBL bit is very important (especially in the
case of ATmega8). By programming this bit, the reset bit is converted into general I/O pin. It
must be noted that while using SPI programmer, one should never program this bit.
Programming this bit would disable the SPI programming since all the SPI programmers use
RESET pin to program the microcontroller (AVR).

CONFIGURING A NEW MICROCONTROLLER

A virgin microcontroller is configured at 1MHz internal RC oscillator with longest start-up and
the JTAG pre-enabled. So the fuse bytes are as follows:

To set the microcontroller for high external frequency with longest start-up and JTAG disabled,
the fuse settings are changed as following.

Implement a simple program to blink a led at PORTA pin 0.

#include<mega16.h>
#include<delay.h>
void main()
{
DDRA=0xFF;
PORTA=OX00;
while(1)
{
portA=0x01;
38
delay-ms(100);
}}

Conclusion

From this lab we learned to understand the fuse bits and the clock speed. Also how to configure
the fuse bit setting of atmega16 microcontroller. This lab also guides the student for hardware
implementation of a task using atmega16

Student’s Comments
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

Lesson Learnt
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
__________________

39
Experiment No. 7
Implement the following program using general purpose (I/O) ports/pins of
atmega16.
 Blink a led at a speed of 1 KHz.
 Send 0-255 on PORTB and check output using LEDS.

Objectives
 To understand GPIO register of atmega16
 To implement some basic tasks using leds and atmega16.

Theory

Generally AVR microcontrollers having four I/O ports named as PORTA, PORTB, PORTC,
PORTD. Take example as ATMEGA8 or ATMEGA 16 or ATMEGA32 microcontrollers, these
are any having four I/O ports and each port having 8 I/O lines and totally each controller having
32 I/O lines. These 32 I/O lines are bi-directional means we can use these I/O lines either input
or output. In addition to each this pin has some of other functions like ADC, timers, interrupts,
serial communication pins and other pins.
To perform any operation with general purpose I/O (GPIO) pins there is a need to configure
three registers.
 DDRx – Data Direction Register
 PORTx – Pin Output Register
 PINx – Pin Input Register

(Here ‘x’ indicates the name of the register A or B or C or D).

40
Configuring the PORT:

If we want to configure one port; there is a need to configure corresponding three registers of the
port. So now we are configuring the PORTc, so we need to configure DDRC, PORTC and PINC
registers.

DDRx register:

GPIO pins are the digital I/O pins i.e. they can act as both input and output.

This register is used to assign the pin of the port as


either input direction or output direction. In this pins are indicated as “DDRxn”, here ‘x’
indicates the port name and ‘n’ indicates the pin number.

41
If DDRxn is written as logic one, the pin is configured as output pin. If DDRxn is written as
logic zero, the pin is configured as input pin.
If pin is configured as input, the internal pull-up resisters will be on. If we want to turn-off the
pull-up resisters, the pin has to be configured as output.
Now take an example of configuring some bits of PORTC as inputs and some bits as outputs.
PORTC has 8 pins, which mean DDRC register has 8-bits as 0-7. In the 8 pins configure 0,2,4,6
pins as inputs and 1,3,5,7 pins as outputs. Generally the register initial value is zero means
register bits are configured to input. So change require bits to logic one to change as
output. Generally we are using shift operation to assign value to bit of register. Take bit0 of
DDRC, the initial value of the bit is zero. If we want to change the bit to one, just we can use
simple shift operation as 1<<DDRC0. If we want to change remaining bits, that is also same but
OR operation is performed between the bits. No we can take the above example and write the
code.
DDRC = (1<<DDRC1) | (1<<DDRC3) | (1<<DDRC5) | (1<<DDRC7);
The above line indicates that setting 1,3,5,7 pins of PORTC as outputs and setting 0,2,4,6 pins of
PORTC as inputs. There is so many ways to perform this operation mentioned below.
DDRC = (1<<1) | (1<<3) | (1<<5) | (1<<7);
DDRC = 0xAA;
DDRC = 0b10101010;

PORTx register

PORTx register is used to control the voltage on the hardware pin. As same like DDRx register,
this PORTx register is also having 8-bits.This register is very useful for setting output pins either
low or high. DDRx register set some bits are input bits and some are output bits. The PORTx
register is very useful to set the value of the output bits/pins as either high or low.
Take the above example, setting some of output pins are low and some of output pins are high.
Here we are setting 1, 5 pins are high and 3, 7 pins are low.
PORTD = (1<<PC1) | (1<<PC5);
PORTD = (1<<1) | (1<<5);
PORTD = 0b00100010;
PORTD = 0x22;

Time Delay

There are three ways to create a time delay.


 Using the timers
 Predefined C function
 by using a simple for loop
Two factors affect the accuracy of the delay

42
 The crystal frequency connected to the X1 – X2 input pins
 The choice of the compiler
Write a C program to send values 00-FF to port PA.

#include <mega16.h>
#include <delay.h>
unsigned char z;
void main(void)
{DDRA=0xff;
PORTA=0x00;
while (1)
{ for ( z=0 ; z<=255 ; z++ )
{PORTA= z;
delay_ms(100); }}}

Write a C program to toggle the bit 2 of the port A.

#include <mega16.h>
#include <delay.h>
#define mybit PORTA.2
void main(void)
{ DDRA=0xff;
PORTA=0x00;
while (1)
{ mybit=~mybit;
delay_ms(100);}}

Conclusion
From this lab we learnt about atmega16 and program using general purpose (I/O) ports/pins of
atmega16. In this lab students will learn how to blink an led at a speed at a given speed. In this
lab students will also implement the given task on hardware.

Student’s Comments
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________
Lesson Learnt
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________

43
______________________________________________________________________________
____________________________________________________________

44
Experiment No. 08
Implement a simple Car Parking System that can accommodate maximum 9
cars using external interrupts in atmega16.

Objectives

 To learn the use of external interrupts in atmega16

Theory

When an interrupt occurs, the normal flow of instructions is suspended by


the microcontroller and the code corresponding to the interrupt, which has occurred, is executed.
Once the code corresponding to the interrupt is executed completely the execution again begins
from the same instruction where it was stopped.

Following is what happens when an interrupt occurs:

 Microcontroller normally completes the instruction which is being executed.


 The program control transfers to Interrupt Service Routine (ISR). Each interrupt have an
associated ISR which is a piece of code which tells the microcontroller what to do when
an interrupt has occurred.
 Execution of ISR is performed by loading the beginning address of the corresponding
ISR into program counter.
 Execution of ISR continues until the return from the interrupt instruction (RETI) is
encountered.
 When ISR is complete, the microcontroller resumes processing where it left off before
the interrupt occurred, i.e., program control is reverted back to the main program.

‘The whole process can be visualized by the following flow diagram:

45
Interrupt Service Routine:

For every interrupt, there is a fixed location in memory that holds the address of its ISR. The
group of memory locations set aside to hold the addresses of ISRs is called the interrupt vector
table. You don’t have to know exact locations of these vectors. Compiler does this for you. For
examples of how to write ISR for different interrupt sources check out tutorials sections for
examples with full source code and detailed explanation.

Atmega16 Interrupts

Number of available interrupts varies with different microcontrollers of AVR family.


Atmega16 in total has twenty one (21) interrupts available. The available interrupts are
categorized in two classes:

1. External Interrupts- Out of the twenty one interrupts available, four interrupts are directly
present on controller pins to handle the interrupts generated by external sources, so they are
called as external interrupts. The four available interrupts and their respective pins are shown in
the figure below in their order of priority:

46
2. Internal Interrupts- The remaining seventeen (17) interrupts are available for internal use
and support the precise and efficient operation of various peripherals like ADC, Timers, and
USARTs etc. The table below describes the available internal interrupts in the order of their
priority:

S. No. INTERRUPT DEFINITION


1 TIMER2 COMP Timer/Counter2 Compare match interrupt
2. TIMER2 OVF Timer2 Overflow interrupt
3. TIMER1 CAPT Timer/Counter1 Capture Event interrupt
4. TIMER COMPA Timer/Counter1 Compare Match A interrupt
5. TIMER COMPB Timer/Counter Compare Match B interrupt
6. TIMER1 OVF Timer/Counter1 Overflow interrupt
7. TIMER0 OVF Timer/Counter0 Overflow interrupt
8. SPI, STC Serial Transfer Complete interrupt
9. USART,RXC USART Receive Complete interrupt
10. USART, UDRE USART Data Register Empty interrupt
11. USART, TXC USART Transmit Complete interrupt
12. ADC ADC Conversion Complete interrupt
13. EE_RDY EEPROM Ready interrupt
14. ANA_COMP Analog Comparator interrupt
15. TWI Two-wire serial interface interrupt
16. TIMER0 COMP Timer/Countrt0 Compare Match interrupt
17. SPM_RDY Store Program Memory Read interrupt

The internal interrupts will be discussed with their respective peripherals. The external interrupts
are mainly focused in this lab.

External Interrupts Configuration Registers:

To configure an external interrupt INT0, INT1 or INT2, it is required to initialize the respective
interrupt by doing appropriate bit settings of following 4 registers. The scope of this document is

47
limited to the explanation of the bits corresponding to interrupts only, the detailed description
about other bits of these register can be found in the datasheet of Atmega16.

1. MCUCR (MCU Control register)

The Bit0, Bit1, Bit2 and Bit3 of MCUCR register determines the nature of signal at which the
interrupt 0 (INT0) and interrupt 1 (INT1) should occur.

2. MCUCSR (MCU Control and Status Register)

The Bit6 of MCUCSR register determines the nature of signal at which the external interrupt 2
(INT2) should occur. INT2 is edge triggered only, it cannot be used for level triggering like
INT0 and INT1.

3. GICR (General Interrupt Control Register)

The GICR register Bit5, Bit6 and Bit7 called the interrupt masks are used to disable/enable the
respective interrupt. Interrupt is disabled when bit value is set to 0 and enabled when bit value is
set to 1. By default all the interrupts are disabled.
48
Above mentioned three registers have to be configured accordingly to initialize a particular
interrupt. Also note that in addition to the above mentioned registers, I-bit (Bit7, Global Interrupt
Enable) of SREG register must also be set to 1. If Global Interrupt enable bit is set to 0, none of
the interrupts will work irrespective of the other register settings. The set and clear of I-bit is
done by SEI and CLI instructions.

// Global enable interrupts


#asm ("sei")
// Global disable interrupts
#asm ("cli")

Programming Steps:

For programming an interrupt, the following steps must be followed:

1. Clear Global Interrupt enable bit in SREG register.


2. Initialize the interrupt by appropriately configuring the MCUCR, MCUCSR and GICR
registers.
3. Set Global Interrupt Enable bit in SREG register.
4. Define the appropriate Interrupt service routine (ISR) for the interrupt.

There are two ways of writing ISR, for e.g. ISR for INT0 can be written in following two ways:

A. ISR (INT0_vect)
B. SIGNAL (SIG_INTERRUPT0)

Example: Let’s write a simple code to get an interrupt working. Initialize INT0 to generate
interrupt at rising edge trigger. The interrupt is generated by using push button which toggle the
LEDs status connected to PORTA. So for enabling INT0, it is needed to set Bit6 of GICR
register, i.e.

GICR= 0x80;
MCUCR=0x03; //For Rising Edge trigger of INT0 the Bit0 and Bit1 status will be-

ISR ROUTINES FOR EXTERNAL INTERRUPTS

Interrupt [EXT_INT0] void ext_int0_isr (void)


{ }

// External Interrupt 1 service routine


Interrupt [EXT_INT1] void ext_int1_isr (void)
{ }

49
// External Interrupt 2 service routine
Interrupt [EXT_INT2] void ext_int2_isr (void)
{ }

//Add a red and green led. Red will glow when parking is maximum i.e the counting reaches 09
and green glows otherwise.

CODE

#include <mega16.h>
Unsigned char count; //global variable for counting cars
Interrupt [EXT_INT0] void car_in (void)
{Count++ ;}

// External Interrupt 1 service routine


Interrupt [EXT_INT1] void car_out (void)
{Count-- ;}

Void main (void)


{ unsigned char display[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
DDRA=0xff; //connect seven segment display with it
PORTA=0x00;

MCUCR=0x0F; //INT0 and INT1 programmed at falling edge


GICR|=0xC0; //General interrupt enable
// Global enable interrupts
#asm ("sei")

While (1)
{
PORTA=display [count]; // select element from display array to show counting on seven
segment display }
}
You can use IR transmitter receiver pair. It will have an analogue output use an OP amp IC to
have a digital value. In class for proteus simulation using simple SPDT switches.

50
Conclusion

From this lab we learned when an interrupt occurs, the normal flow of instructions is suspended
by the microcontroller and the code corresponding to the interrupt, which has occurred, is
executed. Once the code corresponding to the interrupt is executed completely the execution
again begins from the same instruction where it was stopped.

Student’s Comments
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

Lesson Learnt
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

51
Experiment No. 09
Interfacing of Alphanumeric LCD with atmega16
a) Implement a task that will display counting from 0-99 on lcd screen
using atmega16.
b) Implement a task that displays your name on first line and registration
number on second line. It then shifts the displays text towards right at a
readable speed.

Objectives

 To understand the Interfacing of Alphanumeric LCD with atmega16


 To understand to implement a task that displays your name on first line and registration
number on second line.

Theory

The most commonly used Character based LCDs are based on Hitachi's HD44780 controller or
other which are compatible with HD44580.

Explanation
LCD 16 characters ×2 line module
Character construction 5 × 7 dots
Character Pitch 3.65 mm
Dot size 0.55W × 0.5H mm
In the LCD there are either 16-pins or 14-pins and last two pins are for back light and for
initializing LCD, enable pin is stored.

Pin Description
The most commonly used LCDs found in the market today are 1 Line, 2 Line or 4 Line LCDs
which have only 1 controller and support at most of 80 characters. Most LCDs with 1 controller
has 14 Pins and LCDs with 2 controller has 16 Pins (two pins are extra in both for back-light
LED connections). Pin description is shown in the table below.

52
Fig. Character LCD type HD44780 Pin diagram

Table 1: Character LCD pins

Pin No. Name Description


Pin no. 1 VSS Power supply (GND)
Pin no. 2 VCC Power supply (+5V)
Pin no. 3 VEE Contrast adjust
0 = Instruction input
Pin no. 4 RS
1 = Data input
0 = Write to LCD module
Pin no. 5 R/W
1 = Read from LCD module
Pin no. 6 EN Enable signal
Pin no. 7 D0 Data bus line 0 (LSB)
Pin no. 8 D1 Data bus line 1
Pin no. 9 D2 Data bus line 2
Pin no. 10 D3 Data bus line 3
Pin no. 11 D4 Data bus line 4
Pin no. 12 D5 Data bus line 5
Pin no. 13 D6 Data bus line 6
Pin no. 14 D7 Data bus line 7 (MSB)

Table 2: Character LCD pins with 2 Controller

Pin No. Name Description


Pin no. 1 D7 Data bus line 7 (MSB)
Pin no. 2 D6 Data bus line 6
Pin no. 3 D5 Data bus line 5
Pin no. 4 D4 Data bus line 4
Pin no. 5 D3 Data bus line 3

53
Pin no. 6 D2 Data bus line 2
Pin no. 7 D1 Data bus line 1
Pin no. 8 D0 Data bus line 0 (LSB)
Enable signal for row 0 and 1
Pin no. 9 EN1 (1stcontroller)
0 = Write to LCD module
Pin no. 10 R/W 1 = Read from LCD module
0 = Instruction input
Pin no. 11 RS 1 = Data input
Pin no. 12 VEE Contrast adjust
Pin no. 13 VSS Power supply (GND)
Pin no. 14 VCC Power supply (+5V)
Enable signal for row 2 and 3
Pin no. 15 EN2 (2ndcontroller)
Pin no. 16 NC Not Connected

DDRAM - Display Data RAM

Display data RAM (DDRAM) stores display data represented in 8-bit character codes. Its
extended capacity is 80 X 8 bits, or 80 characters. The area in display data RAM (DDRAM) that
is not used for display can be used as general data RAM. So whatever you send on the DDRAM
is actually displayed on the LCD. For LCDs like 1x16, only 16 characters are visible, so
whatever you write after 16 chars is written in DDRAM but is not visible to the user. Figures
below will show you the DDRAM addresses of 1 Line, 2 Line and 4 Line LCDs.

Fig. DDRAM Address for 1 Line LCD

Fig. DDRAM Address for 2 Line LCD

Fig. DDRAM Address for 4 Line LCD

54
CGROM - Character Generator ROM

Now you might be thinking that when you send an ASCII value to DDRAM, how the character
is displayed on LCD? So the answer is CGROM. The character generator ROM generates 5 x 8
dot or 5 x 10 dot character patterns from 8-bit character codes (see Figure a and Figure b for
more details). It can generate 208 5 x 8 dot character patterns and 32 5 x 10 dot character
patterns. User defined character patterns are also available by mask-programmed ROM.

Figure a: LCD characters code map for 5x8 dots

55
Figure b: LCD characters code map for 5x10 dots

As you can see in both the code maps, the character code from 0x00 to 0x07 is occupied by the
CGRAM characters or the user defined characters. If user wants to display the fourth custom
character then the code to display it is 0x03 i.e. when user sends 0x03 code to the LCD DDRAM
then the fourth user created character or pattern will be displayed on the LCD.

56
CGRAM - Character Generator RAM

As clear from the name, CGRAM area is used to create custom characters in LCD. In the
character generator RAM, the user can rewrite character patterns by program. For 5 x 8 dots,
eight character patterns can be written, and for 5 x 10 dots, four character patterns can be written.

BF - Busy Flag

Busy Flag is a status indicator flag for LCD. When we send a command or data to the LCD for
processing, this flag is set (i.e. BF =1) and as soon as the instruction is executed successfully this
flag is cleared (BF = 0). This is helpful in producing and exact amount of delay for the LCD
processing.

To read Busy Flag, the condition RS = 0 and R/W = 1 must be met and The MSB of the LCD
data bus (D7) act as busy flag. When BF = 1 means LCD is busy and will not accept next
command or data and BF = 0 means LCD is ready for the next command or data to process.

Instruction Register (IR) and Data Register (DR)

There are two 8-bit registers in HD44780 controller

 Instruction register
 Data register

Instruction register corresponds to the register where you send commands to LCD e.g. LCD
shift command, LCD clear, LCD address etc. and Data register is used for storing data which is
to be displayed on LCD. When send the enable signal of the LCD is asserted, the data on the pins
is latched in to the data register and data is then moved automatically to the DDRAM and hence
is displayed on the LCD. Data Register is not only used for sending data to DDRAM but also for
CGRAM, the address where you want to send the data, is decided by the instruction you send to
LCD.

Commands and Instruction Set

Only the instruction register (IR) and the data register (DR) of the LCD can be controlled by the
MCU/up. Before starting the internal operation of the LCD, control information is temporarily
stored into these registers to allow interfacing with various MCUs, which operate at different
speeds, or various peripheral control devices. The internal operation of the LCD is determined by
signals sent from the MCU. These signals, which include register selection signal (RS),
read/write signal (R/W), and the data bus (DB0 to DB7), make up the LCD instructions .There
are four categories of instructions that:

57
 Designate LCD functions, such as display format, data length, etc.
 Set internal RAM addresses
 Perform data transfer with internal RAM
 Perform miscellaneous functions

Table 3: Command and Instruction set for LCD type HD44780

58
Although looking at the table you can make your own commands and test them. Below is a brief
list of useful commands which are used frequently while working on the LCD.

Table 4: Frequently used commands and instructions for LCD

No. Instruction Hex Decimal


Function Set: 8-bit, 1
1 0x30 48
Line, 5x7 Dots
Function Set: 8-bit, 2
2 0x38 56
Line, 5x7 Dots
Function Set: 4-bit, 1
3 0x20 32
Line, 5x7 Dots
Function Set: 4-bit, 2
4 0x28 40
Line, 5x7 Dots
5 Entry Mode 0x06 6
Display off Cursor off
(clearing display
6 0x08 8
without clearing
DDRAM content)
7 Display on Cursor on 0x0E 14
8 Display on Cursor off 0x0C 12
Display on Cursor
9 0x0F 15
blinking
10 Shift entire display left 0x18 24
12 Shift entire display right 0x1C 30
Move cursor left by one
13 0x10 16
character
Move cursor right by
14 0x14 20
one character
Clear Display (also
15 0x01 1
clear DDRAM content)
Set DDRAM address or
16 cursor position on 0x80+add* 128+add*
display
Set CGRAM address or
17 set pointer to CGRAM 0x40+add** 64+add**
location

59
* DDRAM address given in LCD basics section
** CGRAM address from 0x00 to 0x3F, 0x00 to 0x07 for char1 and so on..

The table above will help you while writing programs for LCD.

LCD Initialization

Before using the LCD for display purpose, LCD has to be initialized either by the internal reset
circuit or sending set of commands to initialize the LCD. It is the user who has to decide whether
an LCD has to be initialized by instructions or by internal reset circuit.

Initialization by instructions

Initializing LCD with instructions is really simple. Given below is a flowchart that describes the
step to follow, to initialize the LCD.

You can see in the flow chart given below, the LCD is initialized in the following sequence:

1) Send command 0x30 - Using 8-bit interface


2) Delay 15ms
3) Send command 0x30 - 8-bit interface
4) Delay 4.1ms
5) Send command 0x30 - 8-bit interface
6) Delay 100us
7) Send Function set - see Table 4 for more information
8) Display Clear command
9) Set entry mode command - explained below

The first 3 commands are usually not required but are recommended when you are using 4-bit
interface. So you can program the LCD starting from step 7 when working with 8-bit interface.
Function set command depends on what kind of LCD you are using and what kind of interface
you are using (see Table 4 in LCD Command section).

60
Fig. Flow chart for LCD initialization

LCD Entry mode

From Table 3 in command section, you can see that the two bits decide the entry mode for LCD,
these bits are:

a) I/D - Increment/Decrement bit


b) S - Display shift

61
With these two bits we get four combinations of entry mode which are 0x04, 0x05, 0x06, 0x07
(see table 3 in LCD Command section). So we get different results with these different entry
modes. Normally entry mode 0x06 is used which is No shift and auto increment.

Task 01
# include<mega16.h>
# include<delay.h>
#define Rs portB.0
#define E portB.1
#define data port portA
Void writecmnd(char z)
{
RS=0;
Data_port=z;
E=1;
Delay_ms(1);
E=0;
Delay_ms(1);

}
Void writedata (char z)
{
Rs=0;
Data-port=z;
E=1;
Delay_ms(1);
}
Void goto(int add)
{ rs=0;
Add=add+0x80;
Data_port=add;
E=1;
Delay-ms(1);
E=0;
Delay-ms(1);
}
Void display string(char*str)

{
Unsigned char i=0;

62
While(string[i]!=0);
I++;
}
Void lcd_-int()
{
Writecmnd(ox030);
Delay-ms(4);
Writecmnd(0x30);
Writecmnd(ox00);
Delay-ms(15);
Writecmnd(0x38);
Writecmnd(ox0c);
Delay-ms(100);
Writecmnd(0x01);

}
Void main ()
{
DDRA=oxFF;
PORTA=0xoo
Lcd-int();
Displaystring(“name”)
Goyopos(ox40);
Displaystring(“reg.NO”);
While (1)
{
Writecmd(0c1c);
Delay_ms(500);
}

Lab Assignment

Write a simple program that will show counting from 0-99

Conclusion

From this lab we learned the Interfacing of alphanumeric LCD with atmega16 and how to
implement a task that displays your name on first line and registration number on second line.

63
Student’s Comments
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

Lesson Learnt
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

64
Experiment No. 10

Write a simple program to implement an electronic dice using general


purpose I/O ports of atmega16

Objectives

 To implement a basic design problem using GPIO of atmega16


 To learn the use of switches and seven segment display

Theory

You must have played with a dice at some time, for example when playing Yahtzee or
Monopoly. Dice have existed for a very long time. The first known six-sided dice were found in
Iraq and were made in 2750 B.C. They were made of terracotta, with small holes for the spots.
An electrnoc dice is implemented with the help of leds, switches and microcontroller (atmega16)

CODE

#include <mega16.h>
#include <delay.h>

#define on 1
#define sw PINB.0
#define D1 PORTC.0
#define D2 PORTC.1
#define D3 PORTC.2
#define D4 PORTC.3
65
#define D5 PORTC.4
#define D6 PORTC.5
#define D7 PORTC.6

void main(void)
{ int DICE=0;

DDRB=0x00;
DDRC=0xff;
PORTC=0x00;
DDRD=0xff;
PORTD=0x00;

while (1)
{ if(sw==1)
{
switch(DICE)
{
case 1: D4=on; break;
case 2: D3=on;D5=on; break;
case 3: D3=on;D4=on;D5=on; break;
case 4: D1=on;D2=on;D6=on;D7=on; break;
case 5: D4=1; D1=1;D2=1;D6=1;D7=1; break;
case 6:D3=on; D1=on;D2=on;D6=on;D7=on;D5=on; break;
}
delay_ms(100);
PORTC=0X00; }
else
{ DICE++;
PORTD=DICE ;
PORTC=0X00;
if (DICE==7)
DICE=1;} } }

Conclusion

From this lab we learned to implement an electronic dice using general purpose I/O ports of
atmega16 as well as this labs gives a basic insight to implement a real life design problem using
microcontroller.

66
Student’s Comments
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

Lesson Learnt
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

67
Experiment No. 11

Use of timers in atemga16 [Normal mode, polling method and interrupt


method]
a) Implement a task that toggles the state of a led using timer0 after each
32ms.
b) Implement a task that counts up with a delay of 500ms by using
interrupt service routine of timer0 with no prescalar.
Objectives

 To understand the function of timer.


 To study the different modes of timer.
 To study the PWM and time delays.
 To analyze the timer interrupts.

Theory

A timer in simplest term is a register. Timers generally have a resolution of 8 or 16 Bits. So 8 bit
timer is 8Bits wide so capable of holding value within 0-255. But this register has a magical
property! Its value increases/decreases automatically at a predefined rate (supplied by user). This
is the timer clock. And this operation does not need CPU’s intervention.

Fig.: Basic Operation of a Timer.

Timer in Normal Mode

Since Timer works independently of CPU it can be used to measure time accurately. Timer upon
certain conditions take some action automatically or inform CPU. One of the basic condition is
the situation when timer OVERFLOWS i.e. its counted up to its maximum value (255 for 8 BIT
timers) and rolled back to 0. In this situation timer can issue an interrupt and you must write an
Interrupt Service Routine (ISR) to handle the event.

68
Fig.: Basic Operation of a Timer.

Timer in Compare Mode (CTC Mode)

There is another mode of operation for AVR timers are called CTC (Clear on Timer Capture
mode). This mode is called Clear Timer on Compare Match, or CTC. Instead of counting until an
overflow occurs, the timer compares its count to a value that was previously stored in a register.
When the count matches that value, the timer can either set a flag or trigger an interrupt, just like
the overflow case.

Timers can do counting, monitoring external events, keeping time, frequency generation,
generating accurately timed pulses, increment, decrement, Pulse width modulation (PWM) and
for registering the timestamp of external events(Input capture mode).
In principle, a timer is a simple counter.

69
A timer is usually specified by the maximum value to which it can count called MAX beyond
which it overflows and resets to zero is called BOTTOM. The speed of counting can be
controlled by varying the speed of clock input to it.

 Calculate the period of the timer clock T=1/F.


With a crystal of 10 MHz
Time period=1/10x106 =10-5 = 10us

 Divide the desired time delay by the timer clock


Period to calculate the number of increments.

The required time period for the flashing LED at a speed of 20 Hz. is 1/20 i.e. .05 sec. Therefore,
in order for the frequency to be 20Hz, the LED should be toggled every 0.025 sec. Let us find
out the number of timer counts needed to reach 0.025sec.

Timer count=0.025/0.000001=2500
But since the counting starts from 0 and not from 1, we need to go only up to 2499. As this value
cannot be accommodated inside an 8 bit timer we will have to use counter 1 which is of 16 bits.

 Perform 256-n in case of 8 bit timer and 65536-n in case of 16 bit timer. Convert the
value to hexadecimal value (xx) by using a calculator.
Load xx to the TCNT.
i.e. TCNT0=xx

All three units can


 Use prescaler (up to 1024)
 create PWM signals
 create interrupts (overflow, compare event)

Procedure for Generating Time delay

First calculate the time for interrupt to occurs is

70
Time = (1 / Fosc) * TCNT0 value * Prescalar.

 Enable global interrupt (i.e. # asm (“sei”)).


 Select normal mode and the Prescalar for the timer clock in TCCR0
 Enable the Timer/Counter0 Overflow in TIMSK Register
 Load the value to TCNT0.
 Write the operation what we want to do when interrupt occurs in the ISR function

**Note For writing an Interrupt Service Routine function, the function must begin with a
keyword interrupt followed by the vector address with in the square bracket followed by the
name of function with prototype.

What is Prescaler?

A technique to derive a lower frequency from F_CPU, without effecting actual F_CPU to run
timer is called prescaler. In other words it is a mechanism for generating clock for timer by
F_CPU clock. ATMega series of microcontrollers are available in several frequencies such as
1MHz, 8MHz, and 12MHz etc. Prescaler allows us to divide up the incoming clock signal by
power of 2. It reduces the resolution which means that the accuracy has decreased but giving us
the longer timer range.
Prescaler can be set to produce the following clocks:
 No Clock – Timer Stop
 No prescaling – Clock frequency = F_CPU
 F_CPU/8 (23)
 F_CPU/64(26)
 F_CPU/256(28)
F_CPU/1024(210 )

Timer Modes

Timers are usually used in one of the following modes:


1. Normal Mode
2. Fast PWM
3. Phase Correct PWM
4. Clear Timer on Compare Match (CTC) Mode

71
08-bit Timer Registers
TCCR Registers
Timer Counter Control Register – TCCR0

Bit 7 –FOC0 This bit is not required .So we will set it to 0


Bit 6 – WGM00 Wave form Generation Mode (Refer table below)
Bit 5 – COM01 Compare Match Output Mode(Refer table below)
Bit 4 – COM00 Compare Match Output Mode(Refer table below)
Bit 3 – WGM01 Wave form Generation Mode (Refer table below)
Bit 2 – CS02 Clock Select (Refer table below)
Bit 1 – CS01 Clock Select (Refer table below)
Bit 0 – CS00 Clock Select (Refer table below)

Microcontroller has its own frequency of operations (number of operations carried out in 1
sec).
ClkIO is the clock frequency of the microcontroller itself (if microcontroller is working on a
frequency of 16MHz then the value of clkIO = 16 MHz). By pre-scaling we actually adjust the
frequency of counts per second. So, if the pre-scaling factor is chosen to be 64 then the
frequency of timer will be 16MHz/64.

Table shows the prescaling factor for the different values of bits CS02:0
Clock Bit Description

72
Wave form Generation Mode Bit Description

Table shows the COM01:0 bit functionality when the WGM01:0 bits are set to a
Normal or CTC mode (non-PWM).
Compare Match Output Mode, non-PWM Mode

 In first case only timer will be generated and no PWM output will be generated at the OCn
pin
 In second case for one time period the OCn pin will be HIGH and for the succeeding time
period the value of OCn pin will be LOW
 Clear means setting the Output to LOW
 Set means setting the Output to HIGH

Table shows the COM01:0 bit functionality when the WGM01:0 bits are set to fast
PWM mode.

Compare Match Output Mode, Fast-PWM Mode

73
 In first case no Output will be generated on OCn pin
 Second case is reserved. It will not serve our purpose
 Third case will generate a PWM of duty cycle depending upon the value of OCRn and in
non-inverting mode
 Fourth case will generate a PWM of duty cycle depending upon the value of OCRn and in
inverting mode

Table shows the COM01:0 bit functionality when the WGM01:0 bits are set to phase
correct PWM mode.

Compare Match Output Mode, Phase Correct PWM Mode

 In first case no Output will be generated on OCn pin


 Second case is reserved. It will not serve our purpose
 Third case will generate a PWM of duty cycle depending upon the value of OCRn and in
non-inverting mode
 Fourth case will generate a PWM of duty cycle depending upon the value of OCRn and in
inverting mode

TIMSK-Timer/Counter Interrupt Mask Register

TIMSK contains interrupt control bits for all the three Timer/Counters.

Bit Number Description


Bit 7 –OCIE2 Output capture interrupt enable for Timer2
Bit 6 – TICIE2 Output compare match interrupt enable for Timer2

74
Bit 5 – TICIE1 Input capture interrupt enable for Timer1
Bit 4 – OCIE1A Output compare A match interrupt enable for Timer1
Bit 3 – OCIE1B Output compare B match interrupt enable for Timer1
Bit 2 – TOIE1 Overflow interrupt enable for Timer1
Bit 1 – OCIE0 Output compare match interrupt enable for Timer0
Bit 0 – TOIE0 Overflow interrupt enable for Timer0

TIFR-Timer/Counter Interrupt Flag Register


This register contains flag bits for for all the three Timer/Counters.

TOV0 flag is set when the timer overflows from FF 00. The flag bit will remain set till it is
cleared by the software.

Polling Method

In the Polling method, the microcontroller must "access by itself" the device and “ask” for the
information it needs for processing. The microcontroller continuously monitors the status of a
given device. When the condition is met, it performs the device. After that, it moves on to
monitor the next device until everyone is serviced. The microcontroller checks all devices in a
round robin fashion.

75
Interrupt Service Routine:

For every interrupt, there is a fixed location in memory that holds the address of its ISR. The
group of memory locations set aside to hold the addresses of ISRs is called the interrupt vector
table. You don’t have to know exact locations of these vectors. Compiler does this for you. For
examples of how to write ISR for different interrupt sources check out tutorials sections for
examples with full source code and detailed explanation.

So basically when timing is important for microcontroller to react or when it should detect signal
from outside world that occurs relatively rear but lasts for very short interval than interrupt is
better solution.

LAB TASK 1

Implement a program that triggers the state of led using timer 0 after 32ms

#include(mega16.h)
Void main()
{ DDRA.0=1
PORTA.0=0;
TCNTO=0;
TCCRO=0x04;
while(1)
{ If (TCNO=125) }
PORTA.0=~PORTA.0;
TCNTO;}}}

LAB TASK 2

Implements a program that counts upto delay of 500ms using interrupt service routine
(timer 0)

#include <mega16.h>
#include <delay.h>
# define RS PORTB.0
#define E PORTB.1
#define dataport PORTA
Int count =0;
Z=0;
void writecmd(charz)

76
{ RS=0;
Data_port=z;
E=1;
Delay_ms(1); }
Void writedata(char z)
{data_port=z;
E=1;
Delay_ms(1);
E=0;
Delay_ms(1);}
Voud gotopos(int add)
{ Rs=0;
Add=add+0x80;
{data_port=z;
E=1;
Delay_ms(1);
E=0;
Delay_ms(1); }
void distring(char*str)
{ unsigned char I;
I=0;
while (str[i]!=0)
{ Writedata (str[i]);
I++;}}
Void lcd-int()
{Writecmnd(ox03);
Delay-ms(15);
Writecmnd(ox38);
Writecmnd(ox01);
Writecmnd(ox06);
Writecmnd(oxoc);}
void counter()
{TCNT0=56;
Count++;
If(count==2500)
{ Numbdisp(Z);
Count=0;
Z++;
Gotopos(0x00);}}
void main ()

77
{ DDRA=oxFF;
PORTA=oxof;
portB=oxoo;
lcd_int();
tcnto=56;
tccr0=0x01;
timsk=0x01;
#asm(“sei”)}

Conclusion

From this lab we learned to understand the function of timer, to study the different modes of
timer, to study the PWM and time delays and analyze the timer interrupts.

Student’s Comments
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

Lesson Learnt
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

78
Experiment No. 12
Use of timers in atemga16 [CTC mode and Timer as counter]
a) Implement a task that generates a square wave with a variable time
period using CTC mode.
b) Implement a task that counts an event using timer0 and displays the
result on lcd. Also add a led to the circuit that turns on when the
counting reaches 10.
Objectives

 To understand how to implement a task that generates a square wave with a variable time
period using CTC mode
 To understand the task that counts an event using timer0 and displays the result on lcd.
Also add a led to the circuit that turns on when the counting reaches 10.

Theory

Timer Modes:
Timers are usually used in one of the following modes:
5. Normal Mode
6. Fast PWM
7. Phase Correct PWM
8. Clear Timer on Compare Match (CTC) Mode

Modes of Operation

1. Normal Mode

This is the simplest mode of operation. For 8-bit timer TCNT register starts from
BOTTOM (0) and counts till TOP (255). At any point of time you can initialize the
value of TCNT according to your wish and note the value of TCNT at other point of
time. By this you can measure the time taken by the atmega16 to do the operation.
Now time is the number of Timer Clock Cycles multiplying time by the appropriate
value of time for each Timer Clock Cycle (in microseconds) we calculate the time taken
for the operation in microseconds.
The next three modes require one more topic to be covered and that is PWM (Pulse
Width Modulation)

Pulse Width Modulation – PWM

79
As the name suggest we can get a hint that there is a Pulse which is generated here. To
understand this concept consider a Pulse a square wave of voltage vs time.

Now what does Width Modulation mean. It means adjusting the time for which the source
voltage will be HIGH and the time for which the source Voltage will be LOW. We can
control the Width Modulation by using the two properties of this Pulse
 Frequency
 Duty Cycle

Frequency

The frequency is the time period of the Square Wave. Time period correspond to the time for
one voltage cycle (HIGH to HIGH). If we half the frequency, the time period of one
oscillation becomes doubled. So, you can see that is the graph when we adjust the frequency
the width of the oscillation can be adjusted.

Duty Cycle

Duty Cycle is the percentage of time in a time period for which the Voltage is HIGH. The
pulse given in the figure suggests that for half of the time the Voltage is HIGH and for the
Rest half the Voltage is LOW. So, the duty cycle of the Pulse in the given diagram is 50%.

80
In the Above diagram we can see that by adjusting Duty Cycle we can control the Width
Modulation.
So, this was the explanation of Pulse Width Modulation in short. Now continuing with modes
of operation.

Clear Timer on Compare Match Mode (CTC)

In this mode you can set the value of the TOP. So if you set the value of TOP as 100 instead of
255(default TOP value), the TCNT counts from BOTTOM (0) to 100 and then again drops to
BOTTOM (0). So, if the counts of TCNT decrease then the time period of the oscillation
decreases. So, in this mode we can adjust the frequency of the pulse. For Adjusting the TOP
value in this case we use the OCRn (Output Compare Register). In this mode the OCRn pin(for
8-bit timers, OC0 and OC2) is the output pin for PWM.

FAST PWM Mode

In this mode the OCRn pin (for 8-bit timers, OC0 and OC2) is the output pin for PWM of
duty-cycle dependent on the value of OCRn register. The TCNT value goes from
BOTTOM (0) to TOP (255). When the value of TCNT matches with that of the OCR
register, the OC pin can be reset/set according to the mode selected (non-inverting/
inverting). The diagram for How Fast PWM works is given below

81
If you want the output PWM to be of 25% PWM then the TCNT should count from 0 to
63(256/4). So we will initialize the value of OCRn to 63. Now, for non-inverting mode,
TCNT starts counting from 0. When value of TCNTn is less than OCRn the Output is HIGH
at OCn pin and when TCNTn becomes greater than OCRn value then the Output is LOW at
OCn pin. When TCNTn overflows (When there is a transition from MAX to BOTTOM), the
output again becomes HIGH and the cycle continues. So, we can see that for the above case
the output of OCn for one time period remains HIGH for only 1/4th of the time period. So,
the duty cycle for the above case is 25%.

Phase Correct PWM


In this mode the TCNT increases from BOTTOM to MAX and then falls from MAX to
BOTTOM. So in this case the duty cycle will remain same as that in the case of the Fast
PWM but frequency is halved.

82
Task 01
Implement a task that generates a square wave with a variable time period using CTC mode.
#include <mega16.h>
Unsigned int value=125
Interrupt [ext_into]
Void increasing ()
{value =value+125;}
Interrupt [ext_int1]
Void decreasing ()
{value=value_125;}
Interrupt[timo_comp]
Void squarewave ()
{portA.0=~port.0;
Ocro=value;}
Void main()
{ddra=oxff;
portA=oxoo;
mcucr=oxof;
gicr=oxco;
tcnto=0;
ocro=value;
tccro=oxoA;
timsk=oxoz;
#asm(“sei”)
}

83
Task 02
Implement a task that counts an event using timer0 and displays the result on lcd. Also add a led
to the circuit that turns on when the counting reaches 10

Conclusion

From this lab we learned to understand how to implement a task that generates a square wave
with a variable time period using CTC mode also to understand the task that counts an event
using timer0 and displays the result on lcd. Also add a led to the circuit that turns on when the
counting reaches 10.

Student’s Comments
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

Lesson Learnt
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

84
Experiment No. 13

Familiarization to the trainer (MDA 8086). Interfacing 8086 Microprocessor


using 8255 to leds and Seven Segment Display.
a) Write a program for led to blink in order 11, 12, 13, and 14 on the
training kit.
b) Write a program to display the digits in decimal, from 0-9 into 7-
segment display
Objectives

 To understand how program for led to blink in order 11, 12, 13, and 14 on the training kit
 To understand the program to display the digits in decimal, from 0-9 into 7-segment
display

Software: Wincomm

 CPU (CENTRAL PROCESSING UNIT): Using Intel 8086. Using 4.9152 MHz.
 ROM (READ ONLY MEMORY): It has program to control user's key input, LCD
display. user's program. 64K Byte. It has data communication program. Range of ROM
Address is F0000-FFFFFH.
 SRAM (STATIC RANDOM ACCESS MEMORY): Input users program & data.
Address of memory is 00000H-OFFFFH. Totally 64K Bytes.
 DISPLAY: It is LCD (Liquid Crystal Display). 16(Character)x2(Line)

85
 KEYBOARD It is used to input machine language and has 16 of hexa-decimal keys and
8 of function keys.
 SPEAKER Able to test sound using with speaker and further more able to test
synthesizer.
 RS-232C: It is ready to do data communication with IBM compatible personal
computer.
 DOT MATRIX LED: To understand & test of dot matrix structure and principle of
display it is interfaced to P255A (PPI).
 A/D CONVERTER: Convert analog signal to digital signal using with ADC0804.
 D/A CONVERTER: Convert digital signal to analog signal using with DAC0800 and it
is interfaced so as to more Level meter.
 STEP MOTOR INTERFACE: So as to control step motor driver circuit of step motor
is interfaced.
POWER: PC 1101220V. DC +5V 3A. +12V 1A. -12V 0.5A SMPS. (110V/220V)

Introduction to 8255, LED and Seven Segment Display Interfacing to 8086 using 8255

The 8255A is a programmable peripheral interface (PPI) device designed for use in Intel
microprocessor systems. Its function is that of a general purposes I/O component to Interface
peripheral microcomputer system bush. The functional configuration of the
8255A is programmed by the software so that normally no external logic is
necessary to interface peripheral devices.
Functional block of 8255

The 8255 has 24 input/output pins in all. These are divided into three 8-bit
ports.[6] Port A and port B can be used as 8-bit input/output ports. Port C can
be used as an 8-bit input/output port or as two 4-bit input/output ports or to
produce handshake signals for ports A and B.

The three ports are further grouped as follows:

1. Group A consisting of port A and upper part of port C.


2. Group B consisting of port B and lower part of port C.

Eight data lines (D0 - D7) are available (with an 8-bit data buffer) to read/write data into the
ports or control register under the status of the RD (pin 5) and WR (pin 36), which are active

86
low signals for read and write operations respectively. The address lines A 1 and A0 allow to
successively access any one of the ports or the control register as listed below:

A1 A0 Port selected
0 0 port A
0 1 port B
1 0 port C
1 1 control register

The control signal CS (pin 6) is used to enable the 8255 chip. It is an active low signal, i.e.,
when CS = '0', the 8255 is enabled. The RESET input (pin 35) is connected to the RESET line
of system like 8085, 8086, etc., so that when the system is reset, all the ports are initialized as
input lines.

The control register or the command word register is an 8-bit register used to select the modes
of operation and input/output designation of the ports.[

Operational modes of 8255

There are two basic operational modes of 8255:

1. Bit set/reset Mode (BSR Mode).


2. Input/Output Mode (I/O Mode).

The two modes are selected on the basis of the value present at the D 7 bit of the Control Word
Register. When D7 = 1, 8255 operates in I/O mode and when D7 = 0, it operates in the BSR
mode.

Bit set/reset (BSR) Mode

The Bit Set/Reset (BSR) mode is applicable to port C only. Each line of port C (PC 0 - PC7) can
be set/reset by suitably loading the control word register. BSR mode and I/O mode are
independent and selection of BSR mode does not affect the operation of other ports in I/O mode.

8255 BSR mode

87
 D7 bit is always 0 for
BSR mode.
 Bits D6, D5 and D4 are
don't care bits.
 Bits D3, D2 and D1 are
used to select the pin of
Port C.
 Bit D0 is used to set/reset
the selected pin of Port C.

Selection of port C pin is determined as follows:

B3 B2 B1 Bit/pin of port C selected


0 0 0 PC0
0 0 1 PC1
0 1 0 PC2
0 1 1 PC3
1 0 0 PC4
1 0 1 PC5
1 1 0 PC6
1 1 1 PC7

As an example, if it is needed that PC5 be set, then in the control word,

1. Since it is BSR mode, D7 = '0'.


2. Since D4, D5, D6 are not used, assume them to be '0'.
3. PC5 has to be selected, hence, D3 = '1', D2 = '0', D1 = '1'.
4. PC5 has to be set, hence, D0 = '1'.

Thus, as per the above values, 0B (Hex) will be loaded into the Control Word Register (CWR).
D7 D6 D5 D4 D3 D2 D1 D0
0 0 0 0 1 0 1 1
Input/Output Mode

This mode is selected when D7 bit of the Control Word Register is 1. There are three I/O modes:

88
1. Mode 0 - Simple I/O
2. Mode 1 - Strobed I/O
3. Mode 2 - Strobed Bi-directional I/O

Control Word Format

I/O Control Word Format

 D0, D1, D3, D4 are assigned for lower port C, port B, upper port C and port A
respectively. When these bits are 1, the corresponding port acts as an input port. For e.g.,
if D0 = D4 = 1, then lower port C and port A act as input ports. If these bits are 0, then the
corresponding port acts as an output port. For e.g., if D1 = D3 = 0, then port B and upper
port C act as output ports.

 D2 is used for mode selection of Group B (port B and lower port C). When D2 = 0, mode
0 is selected and when D2 = 1, mode 1 is selected.
 D5 & D6 are used for mode selection of Group A ( port A and upper port C). The
selection is done as follows:

D6 D5 Mode
0 0 0
0 1 1
1 X 2

89
 As it is I/O mode, D7 = 1.

For example, if port B and upper port C have to be initialized as input ports and lower port C and
port A as output ports (all in mode 0):

1. Since it is an I/O mode, D7 = 1.


2. Mode selection bits, D2, D5, D6 are all 0 for mode 0 operation.
3. Port B and upper port C should operate as Input ports, hence, D1 = D3 = 1.
4. Port A and lower port C should operate as Output ports, hence, D4 = D0 = 0.

Hence, for the desired operation, the control word register will have to be loaded with 8A (hex).

Mode 0 - Simple I/O

In this mode, the ports can be used for simple I/O operations without handshaking signals. Port
A, port B provide simple I/O operation. The two halves of port C can be either used together as
an additional 8-bit port, or they can be used as individual 4-bit ports. Since the two halves of port
C are independent, they may be used such that one-half is initialized as an input port while the
other half is initialized as an output port.

Mode 0 – input mode

 In the input mode, the 8255 gets data from the external peripheral ports and the CPU
reads the received data via its data bus.
 The CPU first selects the 8255 chip by making CS low. It then selects the desired port
using A0 and A1 lines.
 The CPU then issues an RD signal to read the data from the external peripheral device
via the system data bus.

Mode 0 - Output mode

 In the output mode, the CPU sends data to 8255 via system data bus and then the external
peripheral ports receive this data via 8255 port.
 CPU first selects the 8255 chip by making CS low. It then selects the desired port using
A0 and A1 lines.
 CPU then issues a WR signal to write data to the selected port via the system data bus.
This data is then received by the external peripheral device connected to the selected port.

Mode 1
Strobed I/O mode

90
Mode 2
Strobed Bidirectional I/O mode. Only group A can be initialized in this mode.

INTERFACING OF LED AND SEVEN SEGMENT DISPLAY WITH 8255 O N THE TRAINING KIT

LAB ASSIGNMENT

1. WRITE A PROGRAM FOR LED TO BLINK IN ORDER 11, 12, 13, AND 14 ON THE TRAINING
KIT.
# INCLUDE "MDE8086.H "

VOID WAIT( LONG DEL )


{WHILE( DEL-- );}

VOID MAIN ( VOID )


{UNSIGNED CHAR LED;

OUTPORTB ( PPI1_CR, 0X80 );


OUTPORTB ( PPI1_B, 0 XFF );
OUTPORTB ( PPI1_A, 0 XFF );
OUTPORTB ( PPI1_C, 0X20 );

LED = 0XF1;
DO {
OUTPORTB ( PPI1_B, LED );
LED = LED << 1;
IF( LED & 0X10 ) LED = 0XF1;

91
WAIT(10000 );
} WHILE( 1);}

2. WRITE A PROGRAM TO DISPLAY THE DIGITS IN DECIMAL, FROM 0-9 INTO 7-SEGMENT
DISPLAY.

SEVEN SEGMENT DISPLAY

THE 7 SEGMENT INSIDE THE MDA – 8086 TRAINER KIT CAN BE USED TO DISPLAY NUMBERS .
THIS REQUIRES PIO 8255 PORTS WHICH ARE ALREADY CONNECTED TO THE 7 SEGMENT
INTERNALLY.
THROUGH THE CODE WE CAN ACCESS THESE PORTS AND PROVIDE BINARY OR HEX VALUE TO
SWITCH THE
REQUIRED SEGMENT ON AND OFF.

IN ORDER TO TURN A SEGMENT ON, A LOGICAL 0 IS REQUIRED AS SHOWN BELOW.


ANY NUMBER FROM 0 – 9 CAN BE DISPLAY ON THE 7 SEGMENT BY PROVIDING THE ACTUAL
HEX OR
BINARY VALUE WHICH TURNS THOSE SEGMENTS ON TO DISPLAY THE DIGIT.

# INCLUDE "MDE8086.H "

INT DATA[11] = { 0XC 0, 0XF9, 0XA4, 0 XB 0, 0X 99, 0X92,


0X82, 0XF8, 0X 80, 0X90, 0X00 };

92
VOID WAIT( LONG DEL)
{
WHILE ( DEL-- );
}

VOID MAIN (VOID)


{

INT *DATA1;

OUTPORTB ( PPI1_CR, 0X80 );


OUTPORTB ( PPI1_B, 0 XF0 );
OUTPORTB ( PPI1_C, 0 X00 );

DO {
DATA1 = DATA;

WHILE ( *DATA1 != 0 X00 )


{
OUTPORTB ( PPI1_A, *DATA1 );
WAIT(30000);
DATA1++;
}
}WHILE(1);}

Conclusion

From this lab we learnt about trainer (MDA 8086). Also understand how program for led to blink
in order 11, 12, 13, and 14 on the training kit and to understand the program to display the digits
in decimal, from 0-9 into 7-segment display.

Student’s Comments
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

Lesson Learnt
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________

93
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

Experiment No. 14

Interfacing of 8086 Microprocessor with a 8*8 LED dot Matrix on training kit
MDA 8086.
a) Write a C language program to display a character on the 8*8
LED matrix
b) Write a C language program to display the student’s name on the
8*8 LED matrix.
Objectives

 To understand how to write a C language program to display a character on the 8*8


LED matrix
 To understand the program to display the student’s name on the 8*8 LED matrix

Theory

The KMD D1288C is 1.26 inch height 3mm diameter and 8 × 8 dot matrix LED displays. The
KMD D1288C are dual emitting color type of red, green chips are contained in a dot with milky
and white lens color.

94
DOT-Matrix LED Interface

LED 8*8 MATRIX:

Dot Matrix Display

1. The Dot Matrix inside the MDA – 8086 trainer kit can be used to display any pattern of
LEDs in the dot matrix display.
2. This requires PIO 8255 ports which are already connected to the Dot Matrix internally.
3. Through the code we can access these ports and provide binary or hex value to switch the
required LEDs on and off.
4. In order to turn an LED ON, a logical 0 should be provided to the row and a logical 1
should be provided to the column because of the following arrangement.

For lightening we either give “A” or “B” zero and logic 1 to “C”. By this configuration LED is
forward biased . Port C is controlling rows and port A and B are controlling columns.

A=0*FF (red column)

B=0*FF (green column)

95
Row Line Scanning

Task 01

Write a C language program to display a character on the 8*8 LED matrix

include"mde8086.h"

/* Output Font 'A' */


int font[8] = { 0xff, 0xc0, 0xb7, 0x77,
0x77, 0xb7, 0xc0, 0xff };

void wait(long del)


{
while( del-- );
}

void main(void)
{
int *data;
int common, i;

outportb( PPI2_CR, 0x80 );


outportb( PPI2_A, 0xff );

do{
data = font;
common = 0x01;
for( i = 0; i != 8; i++ ) {
outportb( PPI2_C, common );
outportb( PPI2_B, *data );
96
wait(120);
data++;
common = common << 1;
}
}while(1);
}

Lab task:

Write a C language program to display the student’s name on the 8*8 LED matrix.

Conclusion

From this lab we learnt about C language program to display a character on the 8*8 LED matrix.
Also understand how to program a microprocessor to display the student’s name on the 8*8 LED
matrix.

Student’s Comments
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

Lesson Learnt
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

97
Experiment No. 15
Interfacing of 8086 microprocessor with a A/D convertor on training kit MDA 8086.

Objectives

 To learn to use A/D converter


 To understand the interfacing of A/D convertor with 8086 microprocessor
Theory

ADC stands for analogic to digital converter and permits us to convert analogic voltage levels to
a digital representation, this permits us to read things like the output of a potentiometer, LDR’s,
temperature sensors(like the LM35), humidity sensors, accelerometers and gyroscopes that have
an analogic voltage output, pressure sensors and much more things.

Analog-to-digital converter (ADC) is a device which can convert analogue voltage to digital
numbers so that microcontrollers/microprocessors can handle and process the data. ADCs are the
most widely used devices for data acquisition and control.

There some common and important features about ADCs. For example, resolution of ADC,
response time of ADC, mode of work and method of conversion.

ADC has n-bit resolution; where n can be 8, 12, 16 or even 24 bits. The higher-resolution ADC
provides a smaller step size. Step size is the smallest change that can be recognized by ADC.

8-Bit resolution ADC


If an ADC (e.g.0804) has a resolution of 8 bits, the range is divided into 2^8=256 steps (from 0 –
255). But there are 255 quantization levels.

Where the Vcc is the reference voltage of ADC with n-bit resolution.Below is table in which
Resolution versus Step Size for ADC (if Vcc = 5V) is provided.

98
ADC0804 Chip

There are some control PINs and some input and other are output PINS of ADC0804. The pin
configuration of ADC0804 is shown in the figure below.

Important pins are discussed here in some detail.


CS: Active low input used to activate the ADC0804 chip.

RD (data enable): Active low input used to get converted data out of the ADC0804 chip. When
CS = 0, if a high-to-low pulse is applied to the RD pin, the 8-bit digital output shows up at the
D0-D7 data pins.

WR (start conversion): Active low input used to inform the ADC0804 to start the conversion
process. If CS = 0 when WR makes a low-to-high transition, the ADC0804 starts converting the
analog input value of Vin to an 8-bit digital number. When the data conversion is complete, the
INTR pin is forced low by the ADC0804.

CLK IN and CLK R: Connect to external capacitor and resistor for self-clocking, f =
1/(1.1RC). The clock affects the conversion time and this time cannot be faster than 110 micros.

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

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

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

99
Vref/2: The voltage at Vref/2 (pin9) of ADC0804 can be externally adjusted to convert smaller
input voltage spans to full 8 bit resolution. Vref/2 (pin9) left open means input voltage span is 0-
5V and step size is 5/255=19.6V.

Vref/2 (pin9) (volts) Input voltage span (volts) Step size (mV)
Left open 0–5 5/255 = 19.6
2 0–4 4/255 = 15.69
1.5 0–3 3/255 = 11.76
1.28 0 – 2.56 2.56/255 = 10.04
1.0 0–2 2/255 = 7.84
0.5 0–1 1/255 = 3.92

D0 – D7 output PINs of ADC: D0 – D7 are the digital data output pins. These are the tri-state
buffered and the converted data is accessed only when CS = 0 and RD is forced low. The output
voltage:

The input Vin can be any voltage between 0 V and Vref. When Vin is 0 Vdc, the output is
00000000; when Vin is Vref, the output is 11111111 (255 decimal).

For input voltages between 0 and Vref, the output increases linearly with Vin; therefore, we can
develop a simple ratio for the ADC:
Solving for output gives the following:

where
output = decimal output value of an 8-bit ADC
Vin = analog input voltage to the ADC
Vref = ADC reference voltage

Analog Ground and Digital Ground

Analog ground is connected to the ground of the analog signal while digital ground is connected
to the ground of the Vcc pin.

100
Operation of the ADC

The ADC has two different operating modes. In single conversion mode, each conversion will
be initiated by the user. In free running mode, the ADC is constantly sampling and updating the
ADC Data Registers.

To start the conversion process, a start-conversion pulse is sent to the ADC. The ADC then
samples the analog input and converts it to binary. When completed, the ADC activates the data-
ready output.

Steps for converting the analogue input and reading the output from ADC0804

 Make CS=0 and send a low to high pulse (start-conversion pulse) to WR pin to start the
conversion.
 Now keep checking the INTR pin. INTR will be 1 if conversion is not finished and
INTR will be 0 if conversion is finished.
 If conversion is not finished (INTR=1) , poll until it is finished.
 If conversion is finished (INTR=0), go to the next step.
 Make CS=0 and send a high to low pulse to RD pin to read the data from the ADC

ADC 0804 operating signals

Packaged as a 20-pin DIP, this device can operate on a single 5-Vdc power supply and
requires an external resistor and capacitor to complete the ADC circuit. The start-
conversion pulse is applied to pin 3 (WR), and the data-ready signal comes from pin 5
(INTR). This particular ADC can be connected in a free-running mode where it performs
one conversion after the other as fast as it can.

101
.

Task #01

#define _LCD
#include "mde8086.h"

/* Output Fixed Point


v : Output Data
max : Output Location( Integer Inclusion )
point : Point Location*/
void LCD_putf( long v, int max, int point )
z{
char temp[20];
char temp1[20];
int len, i;

ltoa( v, temp, 10 );
memset( temp1, '0', max );
temp1[max] = 0;

len = strlen( temp );


memmove( temp1+(max-len), temp, len );

/* Output Integer */
for( i = 0; i < max-point; i ++ ) LCD_putch( temp1[i] );

LCD_putch( '.' );
LCD_puts( temp1+i ); }

void main( void )


{ long v;
char buf[20], temp[10];
int i;

LCD_init;
LCD_puts( " Volt Meter" );

102
do {
outportb( ADC, 0xff);
wait( 20000 );

v = inportb(ADC)*(500000l/256);
v /= 100;
LCD_Iout( 0xc5 );
LCD_putf( v, 4, 3 );
LCD_puts( " V" ); }
while( 1);

Conclusion

From this lab we learnt about of A/D convertor with 8086 microprocessor .Also it helps to
understand how to convert the analogue input and reading the output from ADC0804

Student’s Comments
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

Lesson Learnt
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

103
Experiment No. 16
Interfacing of 8086 Microprocessor with a speaker on training kit MDA
8086.In speaker interface the output is the sound of different frequencies and
by changing values of frequency FREQ_TAB, the sound of any frequency can
be obtained.

Objectives

 To learn the use of speaker


 To understand how to interface of 8086 Microprocessor with a speaker on training kit
MDA 8086.

Theory

Task 01

Write a program to interface a speaker with 8086

#include "mda 8086.h"


#define PER 0x0c

104
unsigned char FREQ_TAB[24]={0x25, 0x27, 0x29, 0x2c, 0x2c, 0x31, 0x34, 0x37, 0x36,
0x3e, 0x42, 0x46, 0x4a, 0x4f, 0x54, 0x59, 0x5e, 0x64, 0x6a, 0x7d, 0x77, 0x7e, 0x85,
0xff};
void main (void)
{unsigned char *ptr;
unsigned char i,j,k;
do
{ ptr=FREQ_TAB;
while (*ptr! 0xff)
{j= PER;
k=0xff;
while (j!=0x00)
{outportb (spk,k);
for(i=*ptr;i>0x00;i--);
k=k"0x01;}
ptr++;}
}
while(1);}

Conclusion

From this lab we learnt about to Interface of 8086 Microprocessor with a speaker on training kit
MDA 8086.In speaker interface the output is the sound of different frequencies and by changing
values of frequency we observe different frequency levels.

Student’s Comments
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

Lesson Learnt
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________

105

You might also like