Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 52

Group A: ALP based 8086 Microprocessor

Write Assembly language program (ALP) to add array of N numbers stored in the
memory.
OR

Write ALP to perform non-overlapped and overlapped


block transfer.
Write ALP to convert 4-digit Hex number into its equivalent BCD number and 5-
digit BCD number into its equivalent HEX number. Make your program user
friendly to accept the choice from user for
i. HEX to BCD ii. BCD to HEX 3) EXIT.
Display proper strings to prompt the user while accepting the input and displaying
the result.

3. Write ALP to perform string manipulation to calculate string length and reverse
a string. The strings to be accepted from the user is to be stored in code segment
Module_1 and write FAR PROCEDURES in code segment Module_2 for
following operations on the string:
Concatenation of two strings
Compare two strings

OR
Number of occurrences of a sub-string in the given string
Find number of words, characters, number of lines and number of capital letters
from the given text in the data segment

Note: Use PUBLIC and EXTERN directive. Create .OBJ files of both the
modules and link them to create an EXE file.

Group B: Interfacing with 8086/8051

4. (a) Write 8086 ALP to convert an analog signal in the range of 0V to 5V to its
Corresponding digital signal using either successive approximation ADC or dual
slope ADC.

(b) Write 8086 ALP to interface DAC and generate following waveforms on
oscilloscope,
(i) Square wave - Variable Duty Cycle and frequency.
(ii) Ramp wave - Variable direction,
Trapezoidal wave
Stair case wave

Write 8086 ALP to rotate a stepper motor for given number of steps at a given
angle and in the given direction of rotation based on the user choice.
Any two assignments based on 8086 interfacing (4a-4c)
OR

4.Write ALP to interface 8051 with :


Select any two of the given assignment.
Interfacing DAC and writing programs to generate triangular, trapezoidal and sine
waveforms.
Interfacing 8/12 bit ADC to 8051 or equivalent and to write a program to find out
the average value for 10 readings.
Interface stepper motor to 8051 and write a program to rotate motor with different
step angles and with different speeds.

Any two assignments based on 8051 interfacing (4a-4c)

Group C: File Processing / Dos Commands

5. Write following programs in C using int86, int86x, intdos, intdosx


functions
To delete a file
To create a directory
Read and display disk information such as Drive, tracks, sectors etc
OR

5. Write ALP to read Boot Sector and Display contents of Boot Sector
(use Inline C Code)

6. Write 8086 ALP to perform Encryption and Decryption of a text message.


Program should open, say, FILE1, read the content of FILE1 and encrypt it using
suitable encryption key. Store encrypted text along with encryption key in, say,
FILE2. Read and display the contents of encrypted file i.e. FILE2. Decrypt the
data and store the decrypted data in, say, FILE3. Compare the contents of FILE1
and FILE3 after decryption. Make your program user friendly with proper screen
echoes.
OR

6. Write 8086 ALP to read command line arguments using PSP(Program Segment
Prefix) and implement “DOS COPY Command “. Use File Handle function for
handling the files. Handle all the errors and display appropriate message if user
does not enter proper command line argument.

GroupD: Assignments based on programming 8051 microcontroller.

Write a program to add n, 8 bits numbers found in internal ram location 40H
onwards and store results in R6 and R7.
8. Write a program to multiply 16 bit number by 8 bit number and store the result
and internal memory location.

9. Write a program for block transfer for internal / external memory.

10. Timer programming :ISR based


Write ALP to generate square wave using Timer interrupt on any port pin.

OR
10. Serial port programming : ISR based
Connect two 8051 Ics using serial ports Send FFh and 00H alternatively to
receiver .Output received byte to port1 ,see port1 pin waveform on CRO.
Write ALP to establish communication between two 8051 in asynchronous or
synchronous mode.

11. Write ALP to switch from real mode to protected mode and back to real
mode. Display an appropriate message in each mode
Assignment No.1

Title: Array Addition

Aim: Write an 8086 Assembly Language Program (ALP) to add array of N numbers

stored in the memory.

Objective: To be familiar with the format of assembly language program alongwith


different assembler directives and different functions of the DOS Interrupt.

Theory: Suppose there are ‘n’ numbers stored in memory. Therefore the counter is set to
value n. Also a pointer is set to the point to the base address of memory location where
the data is stored.

Initialize a register, set AL to zero to store resultant addition. Add the numbers
one by one to register while incrementing the pointer and decrementing the counter one
by one till it becomes zero.

Directives Recommended:
1) . model  Initializes memory model before defining any segment.It can be
tiny,small,medium,compact,large.Programmer can choose the memory
model based on the requirement.
2) .data  start of data segment
3) . code start of code segment
4) DB (Define Byte) allocates and initializes bytes of storage
5) EndEnd of the program module.
Instructions Recommended:
MOV, ADD, SUB, INC, DEC, JNZ

Interrupts Recommended:
1) INT 21H, Function 4CH Terminate the code properly and return to the DOS
Prompt.
2) INT 21H, Function 01H Accept a number or character from keyboard
3) INT 21H, Function 02H Display a number or character on the screen.
4) INT 21H, Function 09H Display the string on the screen

Input: An array of N numbers stored in Memory.


OR
An array entered by the user.

Output: Addition of the numbers stored in the array.


OR
Addition of numbers entered in the array.
Main Algorithm:
1) Start
2) Initialize data segment and take array of five numbers for Hex numbers “Hex
array” and numbers stored in ASCII form “ASCII Array” and define sum1=0,
sum2=0 respectively.
3) Initialize counter =5, for addition of five numbers.
4) Add the numbers present in the array one by one, decrementing the counter.
5) Display the result for both the arrays.
6) Stop.

Macros: Not used


Procedures: Not used

Calculations (if any): Addition of N numbers.

Conclusion: Based on the understanding of the concepts used and studied in the
assignment

Platform Used: Windows 2000 professional, Turbo Assembler.

FAQ’s:
1. List and explain different program development tools
2. Explain different types of memory models used
3. What do you mean by initialization of data segment?
4. Explain the procedure of HEX to ASCII conversion and vice versa.

References:
1. Microprocessors and Interfacing 2nd Edition-Douglas Hall
2. Advanced Microprocessors and Peripherals – Ray,Bhurchandi

Assignment No.2
Title: HEX AND BCD Conversion

Aim: Write ALP to convert 4-digit Hex number into its equivalent BCD number
and 5-digit BCD number into its equivalent HEX number. Make your program
user friendly to accept the choice from user for
i. HEX to BCD ii. BCD to HEX 3) EXIT.
Display proper strings to prompt the user while accepting the input and displaying
the result.

Objective: Implementation of conversion process of different numbering system.

Theory:
1. Assembler Directives: different types of assembler directives can be used as
Mention below
 ASSUME: used to told the assembler which logical segment used for each of
physical segment at a given time .
EX. ASSUME CS:CODE _HERE,
DS:DATA_HERE.
 SEGMENT AND ENDS : used to identify a group of data items / instructions that
to be put together n a particular segment .

2. DOS functions: different functions are 01,02,09,4c etc

3. New instructions used with explanation:


 MUL BX : multiply contains of BX and AX and stores result in AX

 DIV BL : divide word in AX by byte in BL ,quotient in AL and remainder in


AH.
 CALL BX: an indirect within segment ,near/ intra-segment call ,BX contains the
offset of first instruction of procedure. Replaces the contains of IP with contains
of register BX
 JNZ label : jump if not zero . in this instruction if zero flag is zero then this
instruction will cause execution to jump to the label given in the instruction
 ROL BL,CL : rotate BL 4 bit position (swap nibbles )
 RET :this RET instruction will return execution from procedure to the next
instruction after the calling instruction which was used in CALL procedure.
I. HEX to BCD

Input: 4 bit HEX number


Output: 5 bit BCD number

Main Algorithm :
1. start
2. select any option from the given MENU
3. select 1 to perform BCD to HEX conversion
4. Select 2 to perform HEX to BCD conversion
5. Select 3 to exit from the given MENU
6. stop

Macros : 1. Name : Message


2. Purpose : To replace the frequently required code of messages
3. I/P: 09 function and 21H interrupt

Procedures:
1. Name : HEX to BCD
2. Purpose
3. I/P : 4 bit HEX number
4.Algorithm for Procedures
i) Start
ii) Get the 4-digit Hex number from the user.
iii) Then go on dividing it by 10 till you get the quotient to be zero.e.g If AX=Hex
no. then AX=AX/10 and remainder in DX is stored in an array.
iv) Read the remainders you got in reverse procedure in comparison to the way you
stored.
v) Thus you get your 5-digit BCD no.
vi) Stop.

II. BCD to HEX

Input: 5 bit BCD number


Output: 4 bit HEX number

Macros : 1. Name : Message


2. Purpose : To replace the frequently required code of messages
3. I/P: 09 function and 21H interrupt

Procedures:
1. Name: BCD to HEX
2. Purpose
3. I/P: 5 bit BCD number
4.Algorithm for Procedures
i) Start
ii) Get the 5-digit BCD number from the user in the form of an array.
iii) Go on multiplying such that (LSB)  01D, (LSB +1) Digit  10D , …… upto
MSB 10000D.
iv) Then go on adding the multiplication results for all BCD digits. The addition
internally performed will be in Hex.
v) Hence display that 4-digit Hex.
vi) Stop

Calculations (if any): not applicable

Conclusion: Based on the understanding of the concepts used and studied in the
assignment

Platform Used: Windows 2000 professional, Turbo Assembler.

FAQ’s:
1. Explain the procedure to convert HEX to BCD and vice versa.
2. Compare MACRO and PROCEDURES.
3. Write algorithm to validate HEX and BCD numbers.

References :
1. Douglas V Hall.,” Microprocessors and Interfacing”

Assignment No.3

Title: String operations


Aim: Write ALP to perform string manipulation to calculate string length and reverse a
string. The strings to be accepted from the user is to be stored in code segment Module_1
and write FAR PROCEDURES in code segment Module_2 for following operations on
the string:
i. Concatenation of two strings
ii. Compare two strings
iii. Number of occurrences of a sub-string in the given string
iv. Find number of words, characters, number of lines and number of
capital letters from the given text in the data segment
Objective: Implementation of string instructions and study types of procedure

Theory:
1. Assembler Directives
 PUBLIC : uses to know the linker that the variable/procedure can be
accessed from other modules
 EXTRN: used to know that the procedures and variables is not in this
module .The EXTRN statement also gives the linker some needed
information about procedures and variables

2. DOS functions : used functions are 01,02 ,09,4CH


3. New instructions used with explanation
 LODS/LODSB/LODSW: this instruction copies a byte from string location
pointed by SI .If direction Flag =0, SI will automatically incremented to point
the next element of the string
 MOVSB : instruction copy a byte from the location pointed by SI register to
location pointed by DI register . IT automatically increment SI pointer to next
source location and automatically increment DI pointer to next destination.
 STOSB: this instruction copies byte from AL to memory location in the extra
segment pointed by DI .If direction Flag is = 0 DI will automatically
incremented by 1 for a byte string or by 2 for word string

Input: Different strings


Output: display of
 Length of entered string
 Displaying entered string in reverse order
 Concatenated two strings
 Compared result of two strings that is “ both are equal or Not”
 Count of occurrences of sub-string
 Detailed display of number of CHRACTERS, WORDS, LINES within
entered string

Main Algorithm :
i) Start
ii) Enter the two string as per the input
iii) enter the choice and accordingly concatenate the two strings/Compare the two
strings/check if 2nd string is substring of 1st string as per the user choice and check
out courses of number of words, capital letters ,number of lines .
iv) display the output .
v) stop

Macro’s :
1. Name : message
2. Purpose: to display the messages by replacing the whole code by simple
macro declaration
3. I/P: 09 function with INT 21H

Procedures: 1
1. Name : Proc_ Reverse _near
2. . Purpose : to display the entered string in reverse order
3. I/P : enter the string
4. Algorithm for Procedures
 Enter the string and to calculate the length of string copy the content from
fist location .and display the length .
 increment SI pointer upto end of string
 Store the length of the string in one counter register
 Display all characters stating from end ,by displaying each character
decrement the counter by 1 until becomes 0

Procedures: 2
1. Name : proc_ concatenate _FAR
2. Purpose : to concatenate the entered two strings
3. I/P : two entered strings
4. Algorithm for Procedures
 For Concatenating operation set one pointer to end of 1st string
 second pointer to start of 2nd string,
 then go on appending the characters of the second string in to the array of first
string till the length of second string is covered.
 Return to main menu
Procedures: 3
1. Name : proc_ compare_ FAR
2. Purpose: to perform comparison between two entered strings and display
result of “ both are equal or Not”
3. I/P : entered strings
4. .Algorithm for Procedures
 For comparing operation set one pointer to the start of 1st string
 second pointer to the start of 2nd string.
 Then first compare the length if length is not equal display message “Strings are
Not equal”
 if length is equal then compare the string character wise, if equal then display
equal strings, otherwise display unequal strings.
 Return to main menu

Procedures: 4
1. Name : proc_ Sub-string_ FAR
2. Purpose: to compare both strings and compare the entered string is sub string of
main string or not.
3. I/P : main and sub string
4. Algorithm for Procedures

 For Substring operations ,enter two strings and initialized one counter = 0
 check for the length of two strings
 if 2nd string length is larger, obviously it is not a substring.
 If 2nd string length is lower than the 1st string length then compare string
character wise.
 If match found then display as 2nd string is substring of first, otherwise 2nd
is not the substring of 1st string.
 If string having match of sub-string increment the count by one and scan
the remaining string in same way to find out multiple occurrences of sub
string upto end of the main string .
 Return to main menu

Procedures: 5
1. Name : proc_ capital_line_word_chracter
2. . Purpose :to display the number of lines ,number of capital characters ,number of
words
3. I/P : entered string
4. .Algorithm for Procedures
 enter the string and store the length of the string .
 compare ASCII value of each character to checkout for capital letters
within the range 65 to 91/ simultaneously checkout 20H for blank space to
calculate the number of words
 display occurrence of capital letters /words/line/character etc

Calculations (if any): not applicable

Conclusion: Based on the understanding of the concepts used and studied in the
assignment

Platform Used: Windows 2000 professional, Turbo Assembler.

FAQ’s :
1. Explain FAR and NEAR procedures
2. Explain the concept of Buffer .
3. Explain the function “0Ah” of interrupt 21h with example.
4. Write down ALP to count number of blank spaces

References :

1. Douglas V Hall.,” Microprocessors and Interfacing”

Programs with comments printouts along with I/P,O/P


Assignment No.4

8051 DAC Interfacing

AIM:
Write ALP to interface 8051 with DAC and writing programs to generate triangular, trapezoidal
and sine waveforms.

THEORY:
Microcontroller is nothing but On-chip computer. It contains ALU, PC, SP, set of registers,
RAM, ROM, I/O on a single chip. The prime use of microcontroller is to control the operation of
a system in proper sequence using the program stored on ROM which does not changes
throughout the lifetime of the system.

8051 is Microcontroller and its basic features are :


 Belongs to MCS51 Family and developed in 1970 by Intel.
 8 bit ALU and 16 bit address lines.
 4K on chip ROM
 128 bytes on chip Data RAM.
 64K PM and 64K DM (External)
 Operating frequency = 10MHz
 4 IO ports (32 bidirectional IO lines)
 Two 16 bit timers
 Full duplex UART
 On-Chip clock oscillator
8051 Registers:
 8 bit accumulator Register

The "R" registers

The "R" registers are a set of eight registers that are named R0, R1, etc. up to and including R7.

These registers are used as auxillary registers in many operations. To continue with the above
example, perhaps you are adding 10 and 20. The original number 10 may be stored in the
Accumulator whereas the value 20 may be stored in, say, register R4. To process the addition you
would execute the command:

ADD A, R4
After executing this instruction the Accumulator will contain the value 30.

You may think of the "R" registers as very important auxillary, or "helper", registers. The
Accumulator alone would not be very useful if it were not for these "R" registers.

The "R" registers are also used to temporarily store values. For example, let’s say you want to
add the values in R1 and R2 together and then subtract the values of R3 and R4. One way to do
this would be:

 The Accumulator
 If you’ve worked with any other assembly languages you will be familiar with the
concept of an Accumulator register.

 The Accumulator, as its name suggests, is used as a general register to accumulate the
results of a large number of instructions. It can hold an 8-bit (1-byte) value and is the
most versatile register the 8051 has due to the shear number of instructions that make use
of the accumulator. More than half of the 8051’s 255 instructions manipulate or use the
accumulator in some way.

 For example, if you want to add the number 10 and 20, the resulting 30 will be stored in
the Accumulator. Once you have a value in the Accumulator you may continue
processing the value or you may store it in another register or in memory.

The Data Pointer (DPTR)

The Data Pointer (DPTR) is the 8051’s only user-accessable 16-bit (2-byte) register. The
Accumulator, "R" registers, and "B" register are all 1-byte values.

DPTR, as the name suggests, is used to point to data. It is used by a number of commands,
which allow the 8051 to access external memory. When the 8051 accesses external memory it
will access external memory at the address indicated by DPTR.

While DPTR is most often used to point to data in external memory, many programmers often
take advantage of the fact that it’s the only true 16-bit register available. It is often used to store
2-byte values, which have nothing to do with memory locations.

The Program Counter (PC)


The Program Counter (PC) is a 2-byte address, which tells the 8051 where the next instruction to
execute is found in memory. When the 8051 is initialized PC always starts at 0000h and is
incremented each time an instruction is executed. It is important to note that PC isn’t always
incremented by one. Since some instructions require 2 or 3 bytes the PC will be incremented by 2
or 3 in these cases.

The Program Counter is special in that there is no way to directly modify its value. That is to say,
you can’t do something like PC=2430h. On the other hand, if you execute LJMP 2430h you’ve
effectively accomplished the same thing.

It is also interesting to note that while you may change the value of PC (by executing a jump
instruction, etc.) there is no way to read the value of PC. That is to say, there is no way to ask the
8051 "What address are you about to execute?" As it turns out, this is not completely true: There
is one trick that may be used to determine the current value of PC. This trick will be covered in a
later chapter.

The Stack Pointer (SP)

The Stack Pointer, like all registers except DPTR and PC, may hold an 8-bit (1-byte) value. The
Stack Pointer is used to indicate where the next value to be removed from the stack should be
taken from.

When you push a value onto the stack, the 8051 first increments the value of SP and then stores
the value at the resulting memory location.

When you pop a value off the stack, the 8051 returns the value from the memory location
indicated by SP, and then decrements the value of SP.

This order of operation is important. When the 8051 is initialized SP will be initialized to 07h.
If you immediately push a value onto the stack, the value will be stored in Internal RAM address
08h. This makes sense taking into account what was mentioned two paragraphs above: First the
8051 will increment the value of SP (from 07h to 08h) and then will store the pushed value at that
memory address (08h).

8051 IO Ports
 4 IO pots – 32 Lines
 All ports are output ports. To make them as an I/P port, 1 has to be written on all pins of
ports.
 Port 1 (8 pins) has internal pull up registers.
 Ports 2 (8 pins) also has internal pull up registers and also acts as a higher order address bus.
 Port 0 does not have pull up registers. It also used as address or data bus. In case of external
memory, port 0 provides both address and data. ALE used for de-multiplexing it.
 Port 3 is 8 bit port and used as for other functionality.
 P 3.0 - RxD (Serial Data Transmission)
 P 3.1 - TxD
 P 3.2 - INT0 (Interrupt 0)
 P 3.3 - INT1 (Interrupt 1)
 P 3.4 - T0 (Timer 0)
 P 3.5 - T1 (Timer 1)
 P 3.6 - WR (Write)
 P 3.7 - RD (Read)

Instruction used:

MOV <dest-byte>,<src-byte>
Function: Move byte variable
Description: The byte variable indicated by the second operand is copied into the location
specified by the first operand. The
source byte is not affected. No other register or flag is affected.
This is by far the most flexible operation. Fifteen combinations of source and destination
addressing modes are
allowed.
Example: Internal RAM location 30H holds 40H. The value of RAM location 40H is 10H. The
data present at input port 1 is
11001010B (0CAH).
MOV R0,#30H ;R0 < = 30H
MOV A,@R0 ;A < = 40H
MOV R1,A ;R1 < = 40H
MOV B,@R1 ;B < = 10H
MOV @R1,P1 ;RAM (40H) < = 0CAH
MOV P2,P1 ;P2 #0CAH
leaves the value 30H in register 0, 40H in both the Accumulator and register 1, 10H in register B,
and 0CAH
(11001010B) both in RAM location 40H and output on port 2.

DJNZ <byte>,<rel-addr>
Function: Decrement and Jump if Not Zero
Description: DJNZ decrements the location indicated by 1, and branches to the address indicated
by the second operand if
the resulting value is not zero. An original value of 00H underflows to 0FFH. No flags are
affected. The branch
destination is computed by adding the signed relative-displacement value in the last instruction
byte to the PC,
after incrementing the PC to the first byte of the following instruction.
The location decremented may be a register or directly addressed byte.
Note: When this instruction is used to modify an output port, the value used as the original port
data will be read
from the output data latch, not the input pins.
Example: Internal RAM locations 40H, 50H, and 60H contain the values 01H, 70H, and 15H,
respectively. The following
instruction sequence,
DJNZ 40H,LABEL_1
DJNZ 50H,LABEL_2
DJNZ 60H,LABEL_3
causes a jump to the instruction at label LABEL_2 with the values 00H, 6FH, and 15H in the
three RAM
locations. The first jump was not taken because the result was zero.
CJNE <dest-byte>,<src-byte>, rel
Function: Compare and Jump if Not Equal.
Description: CJNE compares the magnitudes of the first two operands and branches if their
values are not equal. The branch destination is computed by adding the signed relative-
displacement in the last instruction byte to the PC, after incrementing the PC to the start of the
next instruction. The carry flag is set if the unsigned integer value of <dest-byte> is less than the
unsigned integer value of <src-byte>; otherwise, the carry is cleared. Neither
operand is affected.
The first two operands allow four addressing mode combinations: the Accumulator may be
compared with any
directly addressed byte or immediate data, and any indirect RAM location or working register can
be compared
with an immediate constant.
Example: The Accumulator contains 34H. Register 7 contains 56H. The first instruction in the
sequence,
CJNE R7, # 60H, NOT_EQ
; . . . . . . . . ;R7 = 60H.
NOT_EQ: JC REQ_LOW ;IF R7 < 60H.
; . . . . . . . . ;R7 > 60H.
sets the carry flag and branches to the instruction at label NOT_EQ. By testing the carry flag, this
instruction
determines whether R7 is greater or less than 60H.
If the data being presented to Port 1 is also 34H, then the following instruction,
WAIT: CJNE A, P1,WAIT
clears the carry flag and continues with the next instruction in sequence, since the Accumulator
does equal the
data read from P1. (If some other value was being input on P1, the program loops at this point
until the P1 data
changes to 34H

SJMP
Description: Program control branches unconditionally to the address indicated. The branch
destination is computed by
adding the signed displacement in the second instruction byte to the PC, after incrementing the
PC twice.
Therefore, the range of destinations allowed is from 128 bytes preceding this instruction 127
bytes following it.
Example: The label RELADR is assigned to an instruction at program memory location 0123H.
The following instruction,
SJMP RELADR
assembles into location 0100H. After the instruction is executed, the PC contains the value
0123H.
Note: Under the above conditions the instruction following SJMP is at 102H. Therefore, the
displacement byte of
the instruction is the relative offset (0123H-0102H) = 21H. Put another way, an SJMP with a
displacement of
0FEH is a one-instruction infinite loop.
Bytes: 2
Cycles: 2
Encoding: 1 0 0 0 0 0 0 0 rel. address
Operation: SJMP
(PC) ←(PC) + 2
(PC) ←(PC) + rel

MOVX <dest-byte>,<src-byte>
Function: Move External
Description: The MOVX instructions transfer data between the Accumulator and a byte of
external data memory, which is why
“X” is appended to MOV. There are two types of instructions, differing in whether they provide
an 8-bit or 16-bit
indirect address to the external data RAM.
In the first type, the contents of R0 or R1 in the current register bank provide an 8-bit address
multiplexed with
data on P0. Eight bits are sufficient for external I/O expansion decoding or for a relatively small
RAM array. For
somewhat larger arrays, any output port pins can be used to output higher-order address bits.
These pins are
controlled by an output instruction preceding the MOVX.
In the second type of MOVX instruction, the Data Pointer generates a 16-bit address. P2 outputs
the high-order
eight address bits (the contents of DPH), while P0 multiplexes the low-order eight bits (DPL)
with data. The P2
Special Function Register retains its previous contents, while the P2 output buffers emit the
contents of DPH.
This form of MOVX is faster and more efficient when accessing very large data arrays (up to
64K bytes), since
no additional instructions are needed to set up the output ports.
It is possible to use both MOVX types in some situations. A large RAM array with its high-order
address lines
driven by P2 can be addressed via the Data Pointer, or with code to output high-order address bits
to P2,
followed by a MOVX instruction using R0 or R1.
Example: An external 256 byte RAM using multiplexed address/data lines is connected to the
8051 Port 0. Port 3 provides
control lines for the external RAM. Ports 1 and 2 are used for normal I/O. Registers 0 and 1
contain 12H and
34H. Location 34H of the external RAM holds the value 56H. The instruction sequence,
MOVX A,@R1
MOVX @R0,A
copies the value 56H into both the Accumulator and external RAM location 12H

Digital-to-analog converter
Digital-to-analog converter (DAC or D-to-A) is a device for converting a digital (usually binary)
code to an analog signal (current, voltage or electric charge).An analog-to-digital converter
(ADC) performs the reverse operation.

The DAC0808 is an 8-bit monolithic digital-to-analog converter (DAC) featuring a full


scale output current settling time of 150 ns while dissipating only 33 mW with ±5V
supplies. No reference current (IREF) trimming is required for most applications since the
full scale output current is typically ±1 LSB of 255 IREF/256. Relative accuracies of better
than ±0.19% assure 8-bit monotonicity and linearity while zero level output current of
less than 4 µA provides 8-bit zero accuracy for IREF>=2 mA. The power supply currents
of the DAC0808 is independent of bit codes, and exhibits essentially constant device
characteristics over the entire supply voltage range.
The DAC0808 will interface directly with popular TTL, DTL or CMOS logic levels, and
is a direct replacement for the MC1508/MC1408. For higher speed applications, see

t.

ALGORITHM AND PROGRAM:


Write an 8051 ALP to generate following waveforms using Digital to Analog converter.
 Square wave
 Triangular wave
 Sawtooth wave
 Trapezoidal wave
 Sine wave

a) To generate a square waveform.

With 00 as input to DAC, the analog output is 0v. Similarly, with FFh as input, the output is +5v,.
Outputting digital data 00 and FF at regular intervals to DAC, results in a square wave of
amplitude 5 volts.

Algorithm
1. START
2. Load FFC0 address in DPTR (Data Pointer)
3. Load A with 00 and output it to DPTR Address.
4. Call the delay subroutine
5. Load A with FF and output it to DPTR Address
6. Call the delay subroutine
7. Jump back to step 2
8. STOP

Program
b) To generate a triangular waveform

With 00 as input to DAC, the analog output is 0v. Incrementing this value by step 1, the analog
voltage increases and finally it reaches to +5v (when the value is FFh). Start decrementing this
value to 00h will decrease the output voltage to 0v creates triangular waveform.

Algorithm
1. START
2. Load FFC0 address in DPTR (Data Pointer)
3. Load A with 00 and output it to DPTR Address.
4. Increment Accumulator and Output it to DPTR Address.
5. Compare it with FFh
6. If A is not FF then jump to step 4.
7. Decrement A and Output it to DPTR address.
8. If A is not 00 then jump to step 7.
9. Jump back to step 3
10. STOP

Program

c) To generate a sawtooth waveform

With 00 as input to DAC, the analog output is 0v. Incrementing this value by step 1, the analog
voltage increases and finally it reaches to +5v (when the value is FFh). Suddenly outputting 00h,
the analog output voltage is 0v which creates sawtooth waveform.

Algorithm
1. START
2. Load FFC0 address in DPTR (Data Pointer)
3. Load A with 00 and output it to DPTR Address.
4. Increment Accumulator and Output it to DPTR Address.
5. Compare it with FFh
6. If A is not FF then jump to step 4.
7. Jump back to step 3
8. STOP

Program

d) To generate a Trapezoidal waveform

With 00 as input to DAC, the analog output is 0v. Incrementing this value by step 1, the analog
voltage increases and finally it reaches to +5v (when the value is FFh). After then we can call
delay procedure. Start decrementing this value to 00h will decrease the output voltage to 0v and
call delay procedure again will create Trapezoidal waveform.

Algorithm
1. START
2. Load FFC0 address in DPTR (Data Pointer)
3. Load A with 00 and output it to DPTR Address.
4. Increment Accumulator and Output it to DPTR Address.
5. Compare it with FFh
6. If A is not FF then jump to step 4.
7. Call Delay procedure
8. Decrement A and Output it to DPTR address.
9. If A is not 00 then jump to step 8.
10. Call Delay procedure.
11. Jump back to step 3

Program

e) To generate a sine waveform

Algorithm
1. START
2. Load Count Value (24h) in R2 Register.
3. Load memory address of starting lookup table into R0 and R1.
4. Load A with the content of DPTR and output it to FFC0h
5. Increment memory Pointer to point it to the next location.
6. Decrement Counter value (R2),
7. If Counter is not 00, go to step 4.
8. Jump back to step 2.
9. STOP

Program
ASSIGNMENT NO 6
8051 ADC Interfacing

AIM: Write ALP to interface 8051 with ADC

THEORY:

Interfacing 0f ADC 0809 TO 8951

In our daily life, anything we deal like sound, pressure, voltage or any measurable quantity are
usually in analog form So what if we want to interface any analog sensor with our digital
controllers. There must be something that translate the analog inputs to digital output, and so
Analog to digital converters come to play. Usually we call them ADC (Analog to digital
converter). The basic principle of operation is to use the comparator principle to determine
whether or not to turn on a particular bit of the binary number output. It is typical for an ADC to
use a digital-to-analog converter (DAC) to determine one of the inputs to the comparator.

Following are the most used conversion methods:


 Digital Ramp ADC
 Successive Approximation ADC
 Flash ADC
Successive Approximation ADC

The successive approximation ADC is much faster than the digital ramp ADC because it uses
digital logic to converge on the value closest to the input voltage. A comparator and a DAC are
used in the process. A flowchart explaining the working is shown in the figure below.

Features of ADC 0809


1. 8 bit Resolution
2. 100 usec Conversion Time
3. 8 Channel Multiplexer with latched control logic
4. Low power Consumption 15 mw
5. Latch with tri-state output
ADC808/809 Chip with 8 analog channel. This means this kind of chip allows to monitor 8
different transducers particular input channel is selected by using Address decoder. Address is
latched into the decoder on the low to high transition of ALE. A the positive edge of SOC,
successive approximation register is reset. The conversion began on the falling edge of SOC. End
of conversion will go LOW between 0 to 8 clock pulses after the SOC signal

AGORITHM:

For ADC 0808/809 


Notice that the ADC808/809 that there is no self-clocking and the clock must be provided from
an external source to the CLK pin. (you can use programmable clock oscillator to enable or
disable clock by programmable bit.)
1. Select an analog channel by provide bits to A, B, C.
2. Enable clock
3. Activate ALE with a low-to-high pulse.
4. Activate SC with a high-to-low pulse (start conversion) The conversion is begun on the
falling edge of the start conversion pulse.
5. Moniter EOC PULSE
6. After conversion this pin goes high.
7. Activate OE with a high-to-low pulse to read data out of the ADC chip.
8. Read Digital input

PROGRAM

CLR bit
Operation: CLR
Function: Clear bit
Description: CLR bit clears the indicated bit (reset to 0). No other flags are affected. CLR can
operate on the carry flag or any directly addressable bit.
Example: Port 1 has previously been written with 5DH (01011101B). The following
instruction,CLR P1.2 leaves the port set to 59H (01011001B).

MOV <dest-byte>,<src-byte>
Function: Move byte variable
Description: The byte variable indicated by the second operand is copied into the location
specified by the first operand. The source byte is not affected. No other register or flag is affected.
This is by far the most flexible operation. Fifteen combinations of source and destination
addressing modes are allowed.
Example: Internal RAM location 30H holds 40H. The value of RAM location 40H is 10H. The
data present at input port 1 is 11001010B (0CAH).
MOV R0,#30H ;R0 < = 30H
MOV A,@R0 ;A < = 40H
MOV R1,A ;R1 < = 40H
MOV B,@R1 ;B < = 10H
MOV @R1,P1 ;RAM (40H) < = 0CAH
MOV P2,P1 ;P2 #0CAH
leaves the value 30H in register 0, 40H in both the Accumulator and register 1, 10H in register B,
and 0CAH
(11001010B) both in RAM location 40H and output on port 2
NOP
Function: No Operation
Description: Execution continues at the following instruction. Other than the PC, no registers or
flags are affected.
Example: A low-going output pulse on bit 7 of Port 2 must last exactly 5 cycles. A simple
SETB/CLR sequence generates a one-cycle pulse, so four additional cycles must be inserted. This
may be done (assuming no interrupts are enabled) with the following instruction sequence,
CLR P2.7
NOP
NOP
NOP
NOP
SETB P2.7
Bytes: 1
Cycles: 1
Encoding: 0 0 0 0 0 0 0 0
Operation: NOP

RET
Function: Push onto stack
Description: The Stack Pointer is incremented by one. The contents of the indicated variable is
then copied into the internal
RAM location addressed by the Stack Pointer. Otherwise no flags are affected.
Example: On entering an interrupt routine, the Stack Pointer contains 09H. The Data Pointer
holds the value 0123H. The
following instruction sequence,
PUSH DPL
PUSH DPH
leaves the Stack Pointer set to 0BH and stores 23H and 01H in internal RAM locations 0AH and
0BH,
respectively.
Function: Return from subroutine

Description: RET pops the high- and low-order bytes of the PC successively from the stack,
decrementing the Stack Pointer by two. Program execution continues at the resulting address,
generally the instruction immediately following an ACALL or LCALL.

ACALL addr11
Function: Absolute Call
Description: ACALL unconditionally calls a subroutine located at the indicated address. The
instruction increments the PC twice to obtain the address of the following instruction, then pushes
the 16-bit result onto the stack (low-order byte first) and increments the Stack Pointer twice. The
destination address is obtained by successively concatenating the five high-order bits of the
incremented PC, opcode bits 7 through 5, and the second byte of the instruction. The subroutine
called must therefore start within the same 2 K block of the program memory as the first byte of
the instruction following ACALL.
No flags are affected.
Example: Initially SP equals 07H. The label SUBRTN is at program memory location 0345 H.
After executing the following nstruction,
ACALL SUBRTN
at location 0123H, SP contains 09H, internal RAM locations 08H and 09H will contain 25H and
01H, respectively, ANd the PC contains 0345H

JNB bit,rel
JNC rel
Function: Jump if Bit Not set
Description: If the indicated bit is a 0, JNB branches to the indicated address; otherwise, it
proceeds with the next instruction.The branch destination is computed by adding the signed
relative-displacement in the third instruction byte to thePC, after incrementing the PC to the first
byte of the next instruction. The bit tested is not modified. No flags areaffected.
Example: The data present at input port 1 is 11001010B. The Accumulator holds 56H
(01010110B). The following instruction sequence,
JNB P1.3,LABEL1
JNB ACC.3,LABEL2
causes program execution to continue at the instruction at label LABEL2.

SETB <bit>
Function: Set Bit
Description: SETB sets the indicated bit to one. SETB can operate on the carry flag or any
directly addressable bit. No other
flags are affected
Example: The carry flag is cleared. Output Port 1 has been written with the value 34H
(00110100B). The following instructions,
SETB C
SETB P1.0
sets the carry flag to 1 and changes the data output on Port 1 to 35H (00110101B).

Assignment No.7

TITLE – C programming using int86, int86x, intdos, intdosx functions .

AIM: - Write following programs in C using int86, int86x, intdos, intdosx functions
i. To delete a file
ii. To create a directory
iii. Read and display disk information such as Drive, tracks, sectors
etc

OBJECTIVE : -
1. To study use of BIOS & DOS functions in C programs using int86, int86x,
intdos, intdosx functions
THEORY : -
1 int86, int86x, intdos, intdosx functions

“Union” & “Structure”


 Derived Data Type, Both are used to group a no. of variables together.
 Structure - Enable us to treat a no. of variables stored at different place in
memory.
 Union - Enable us to treat the same space in memory as no. of different
variables. In simple, a union offers a way for a section of memory to be
treated as a variable of one type on one occasion and as a different variable of
different type on another occasion.

Int 86() - ROM BIOS function

 To make S/W interrupt occurrence and invoke ROM-Bios function.


 The function needs 3 arguments
1. Interrupt no.
2. Two union var.
 First one for : passing values to ROM-BIOS routine
 Second one for : returning values from ROM-BIOS routine.
Ex.
Int 86(16, &inregs,&outregs);
Where
- 16 is interrupt no.
- inregs: values being sent to ROM- BIOS function.
- outregs: values being returned by ROM- BIOS function.

NOTE: int 86() requires only addresses of union not union values.

Using the Declarations in dos.h


 Actually , structures WORDREGS & BYTEREGS
union REGS are already declared in dos.h file.
 Inclusion of this file solve the purpose of program.

Intdos() - Dos Interrupt functions.


 To invoke DOS interrupt

Int 86x() & intdosx() : used to invoke ROM_BIOS & DOS services respectively,if
service requires use of DS & ES reg. else int 86() & intdos() are used

2. List of DOS functions used : -


Program uses File handle function and for all file handle functions following terms are
common & important.
i. File Handle
An integer assigned to a file by DOS
Used to refer to the file in programs
DOS provides file handle functions to manipulate files
– These are available through the DOS interrupt (21h)
Predefined File Handles
DOS manages standard input output devices through these handles
– 0 keyboard (stdin)
– 1 screen (stdout)
– 2 error output (stderr)
– 3 auxiliary device
– 4 printer
ii. File Errors
Many file handling routines return an error code
– carry clear indicates no error
– carry set indicates an error
– AX will contain some output or an error code
1 invalid function number
2 file not found
3 path not found
4 no free handles
5 access denied
6 invalid handle
C invalid access code
F invalid drive
10 can't remove current dir
11 not the same device
12 no more files to be found

1. INT 21H, FUNCTION 41H : DELETE FILE


Deletes a file from the specified or default disk and directory.
Call with
– AH is 41h
– DS:DX is the address of filename (ASCIIZ)
Returns CF = 0 if successful or error code through AX
2. INT 21H, FUNCTION 39H : Create Directory
Creates a directory using the specified drive and path
Call with
– AH is 39h
– DS:DX is = segment:offset of ASCIIZ pathname
Returns CF = 0 if successful or error code through AX
The function fails if :
any element of the pathname does not exist.
a directory with the same name at the end of the same path already
exists.
the parent directory for the new directory is the root directory and
is full.
the program is running on a network and the user running the
program has insufficient access rights.
3. List of ROM BIOS functions used :

1. INT 13H, Function 08H : Get drive parameters


Returns various parameters for the specified drive.
Call with:
o AH = 08H
o DL = drive
 00H floppy disk
 80H fixed disk
Returns:
If function successful ( Carry flag = clear )
o BL = drive type (PC/AT and PS/2 floppy disks)
 01H if 360 KB, 40 track, 5.25"
 02H if 1.2 MB, 80 track, 5.25"
 03H if 720 KB, 80 track, 3.5"
 04H if 1.44 MB, 80 track, 3.5"
o CH = low 8 bits of maximum cylinder number
o CL = bits 6 & 7 high-order 2 bits of maximum cylinder number
bits 0 to 5 maximum sector number
o DH = maximum head number
o DL = number of drives
o ES:DI = segment:offset of disk drive parameter table
If function unsuccessful ( Carry flag = set )
o AH = Error code.
Functions Used :
1. Create _Directory :
Purpose : Accepts path name of the directory to be created
& creates new directory with accepted name.
Input – Pathname of the directory to be created.
Output : New directory created with accepted name.
Caller Program : Main
Calling Program : Nil

2. Display_Disk_Info :
Purpose : Reads & displays drive parameters of drive A
Input – Nil
Output : Displays disk information.
Caller Program : Main
Calling Program : Nil

3. Delete_File :
Purpose : Accepts pathname of the file to be deleted & deletes that
file.
Input – Pathname of the file to be deleted.
Output : Deletion of the specified file..
Caller Program : Main
Calling Program : Nil

MAIN ALGORITHM:-

1. Display menu 1. Create Directory 2. Display Disk Information


3. Delete File 4. Exit
2. Accept choice from the user
a. If choice = 1, call function Create _Directory and goto step 1
b. If choice = 2, call function Display_Disk_Info and goto step 1
c. If choice = 3, call function Delete_File and goto step 1
d. If choice = 4, Terminate the program.

Algorithm for function Create _Directory

1. Accept name of the directory to be created, and store it in buffer.


2. Create new directory with Intsosx, function 39h.
3. Check the status of carry flag returned by Intdosx & display appropriate
message.
4. Return.

Algorithm for function Display_Disk_Info

1. Get disk information with BIOS function through Int86, function 13h.
2. If the value returned by Int86 is 0, Read drive parameters like media
descriptor, Number of tracks & number of sectors returned by Int86 & display
the same on screen otherwise display appropriate error message
3. Return.

Algorithm for function Delete_File

1. Accept the path name of the file to be deleted in the buffer.


2. Delete file with Intdosx, function 41h.
3. Check the status of carry flag returned by Intdosx & display appropriate
message.
4. Return.

Conclusion : Rom BIOS & DOS functions are implemented successfully in C


program through INT86(), INTDOS(),INT86X(), INTDOSX()

Platform Used : DOS, TC, TLINK, TD

References : MS DOS Programming by Ray Duncan

FAQ’s :
1. What is Union? What is structure?
2. What is difference between union & structure?
3. What is INT86(), INTDOS(),INT86X(), INTDOSX()?
4. What is difference between INT86() & INTDOS()?
5. What is difference between INT86() & INT86X()?
6. What is difference between INTDOS() & INTDOSX()?
7. What is disk structure?
8. What is head, track & sector of a disk?

Program listing with input, output

ASSIGNMENT NO: - 08

TITLE – Simulation of DOS COPY command.

AIM: - Write 8086 ALP to read command line arguments using PSP (Program Segment
Prefix) and implement “DOS COPY Command “. Use File Handle function for handling
the files. Handle all the errors and display appropriate message if user does not enter
proper command line argument.

OBJECTIVE: -
2. To study PSP (Program Segment Prefix) & its use to read command line
arguments to implement command line interface.
3. To study file handle DOS functions.

THEORY: -
1. PSP (Program Segment Prefix)
A thorough understanding of the program segment prefix is vital to successful
programming under MS-DOS.
It is a reserved area, 256 bytes long, that is set up by MS-DOS at the base of the
memory block allocated to a transient program.
The PSP contains some linkages to MS-DOS that can be used by the transient
program, some information MS-DOS saves for its own purposes, and some
information MS-DOS passes to the transient program to be used or not, as the
program requires

The Program Segment Prefix Structure


2. List of Assembler directives used - .model, .data, .code, end, db, dw.

3. List of DOS functions used : -


Program uses File handle functions and for all file handle functions following terms are
common & important.
i. File Handle
An integer assigned to a file by DOS
Used to refer to the file in programs
DOS provides file handle functions to manipulate files
– These are available through the DOS interrupt (21h)
Predefined File Handles
DOS manages standard input output devices through these handles
– 0 keyboard (stdin)
– 1 screen (stdout)
– 2 error output (stderr)
– 3 auxiliary device
– 4 printer
ii. File Errors
Many file handling routines return an error code
– carry clear indicates no error
– carry set indicates an error
– AX will contain some output or an error code
1 invalid function number
2 file not found
3 path not found
4 no free handles
5 access denied
6 invalid handle
C invalid access code
F invalid drive
10 can't remove current dir
11 not the same device
12 no more files to be found

3. INT 21H, FUNCTION 3CH : CREATE FILE


Creating a new file
Call with
– AH is 3Ch
– DS:DX is the address of filename (ASCIIZ)
– CX is attribute
Bit Significance
– 0 read-only
– 1 hidden
– 2 system
– 3 volume label
– 4 reserved
– 5 archive
– 6-15 reserved
Returns file handle in AX if successful or error code 3, 4, or 5

4. INT 21H, FUNCTION 3DH : OPEN FILE


Opening a Existing file
Call with
– AH is 3Dh
– DS:DX is the address of filename (ASCIIZ)
– AL is access code
0 read
1 write
2 read/write
Returns file handle in AX if successful or error code 2,4,5,12

5. INT 21H, FUNCTION 3EH : CLOSE FILE


Closing a file frees the file handle and updates file info (size, timestamp) in
directory
– AH is 3Eh
– BX is the file handle
Returns error code 6 in AX if unsuccessful

6. INT 21H, FUNCTION 3FH : READ FILE


If a file is open for reading, this function will copy a specified number of bytes
from the file to a memory buffer
EOF is detected by comparing CX and AX after the read
Call with
– AH is 3Fh
– BX is file handle
– CX is number of bytes to read
– DS:DX is address of buffer
Returns number of bytes read in AX if successful or error code 5 or 6

7. INT 21H, FUNCTION 40H : WRITE FILE


This function sends one or more bytes to a file that is open for output
A full disk will result in less than the specified number of bytes being written
Call with
– AH is 40h
– BX is file handle
– CX is number of bytes to write
– DS:DX is address of bytes to be written
Returns number of bytes written in AX if successful or error code 5 or 6

8. INT 21H, FUNCTION 4EH : FIND FILE


Searches the default or specified directory on the default or specified drive for the
first matching file.
– AH is 4Eh
– CX is the search attribute
– DS:DX is the address of filename (ASCIIZ)
Successful operation (c=0) indicates file found or unsuccessful operation Returns
error code in AX.

9. INT 21H, FUNCTION 5BH : CREATE FILE


(Supported in version 3.0 and later)
Creates a file and returns a handle that can be used by the program for subsequent
access to the file. If a file with the same name already exists, the function fails.
Call with
– AH is 5Bh
– CX is the attribute
– DS:DX is the address of filename (ASCIIZ)
Successful operation (c=0) indicates file creation and returns file handle through
AX or unsuccessful operation (c=1) Returns error code in AX.

10. INT 21H, Function 62H : GET PSP BASE ADDRESS


Obtains the segment address of the program segment prefix ( PSP ) for the
currently executing program.
Call with
– AH is 62h
Returns
– BX = segment address of the PSP

MAIN ALGORITHM: -

1. Get base address of PSP ( 62h or 51h func. of DOS int 21h )
2. Check for required number of arguments i.e., 2. If there are invalid arguments,
then display appropriate error msg (No, insufficient or too many parameters) and
terminate.
3. Get command line arguments i.e. Source filename & destination filename from
PSP and store it in respective buffers.
4. Check whether source file exists (4Eh func. Of INT 21h. ). If not display
appropriate error msg and terminate.
5. Check whether destination file exists (5BH function of int 21h). if the file
already exists ( c=1 ) ask user whether wants to overwrite? If yes, then create
file using 3CH function otherwise terminate.
6. Open source file using 3DH function in read mode. Check for error in opening a
file, if yes display appropriate error msg. and terminate.
7. Read the record from source file in a buffer using 3FH function. Check for
error in reading file, if yes display appropriate msg and terminate.
8. Check for end of source file by comparing AX ( Bytes actually read ) with 0, if
equal (EOF) goto step 11.
9. Write the record ( with length = no. of bytes actually read in earlier read ) from
buffer into the destination file using 40H function. Check for error in writing
file, if yes display appropriate error msg. and terminate.
10. Go to step 7.
11. Close both the files (3FH function of int 21h).
12. Safe termination and exit to Dos using 4Ch func. Of INT 21h

Macro’s Used :
1. Message : Message Macro Msg
Purpose : It is used to display a message.
Input : msg (dummy parameter)
Output : It displays the message on the screen

Procedures Used : Nil

Conclusion : DOS COPY command is successfully implemented in assembly with


command line interface

Platform Used : DOS, TASM, TLINK, TD

References : MS DOS Programming by Ray Duncan


FAQ’s :

9. What is PSP? What is its structure?


10. Who creates PSP? What is its purpose?
11. What is command tail block of PSP? What is its starting address & size?
12. What is command line interface?
13. What is syntax of DOS COPY command?
14. What is file handle function?
15. What is ASCIIZ pathname, file handle & error code with respect to file handle
function?
16. How to identify end of file ( EOF ) for a file?

Program listing with input, output :

Assignment No. – 9

Title: Addition of n 8-bit numbers


Aim: To write a program to add n, 8 bits numbers found in internal RAM locations 40H
onwards and store results in R6 and R7.

Objective: i) To perform arithmetic operations using 8051


ii) To learn internal memory access of 8051

Theory: The 8051 memory is divided into the following 4 physical parts as shown in
figure 1.
1. Internal RAM
2. Internal special function registers
3. External RAM
4. Internal and external ROM

Addresses
7F General
Purpose
30 Area
2F Bit
Address
20 Area
1F Register
18 Bank 3
17 Register
10 Bank 2
0F Register
08 Bank 1
07 Register
00 Bank 0
Fig. 1Internal RAM

Here we need to access internal memory to take input and to store the output.

Internal RAM: Internal memory organization is shown in fig.1. It is divided into three
distinct areas:
1) 32 bytes from address 00H to 1FH that make up 32 working registers organized as 4
banks of eight registers each. The 4 registers banks are numbered 0 to 3 and are made up
of 8 registers named R0 to R7. Each register can be addressed by name or by its RAM
address. Bits RS0 and RS1 in the PSW determine which bank of registers is currently in
use at any time when the program is running. Bank 0 is selected on reset.

7 6 5 4 3 2 1 0
CY AC F0 RS1 RS0 OV ------ P
The Program Status Word (PSW) Special Function Register

Bit Symbol Function


7 CY Carry flag
6 AC Auxiliary Carry flag
5 F0 User flag 0
4 RS1 Register bank select bit 1
3 RS0 Register bank select bit 0
RS1 RS0
0 0 Select register bank 0
0 1 Select register bank 1
1 0 Select register bank 2
1 0 Select register bank 3
2 OV Overflow flag
1 ---- Reserved for future use
0 P Parity flag
Bit addressable as PSW.0 to PSW.7

2) A bit addressable area of 16 bytes occupies RAM byte addresses 20H to 2FH forming
a total of 128 addressable bits. An addressable bit may be specified by its bit address of
00H to 7FH or byte address from 20H to 2FH. Addressable bits are useful when the
program need only remember a binary event.

3) A general purpose RAM area above the bit area from 30H to 7FH, addressable as
bytes.

Instructions used:

1) MOV dest, src


This instruction copies a byte from source location to the destination. There are fifteen
possible combinations for the instruction. It does not affect flags.

MOV A, Rr Copy data from register Rr to register A


MOV Rr, A Copy data from register A to register Rr.
Rr can be any register from R0 to R7
Here register addressing mode is used. A data MOV does not alter the contents of the
data source address. A copy of the data is made from source and moved to the
destination address. The contents of the destination are replaced by the source contents.

e. g. MOV R1, A Copy data from register A to register R1


MOV A, R1 Copy data from register R1 to register A

2) ADD A, src
This instruction adds the source byte to the accumulator (A) and places the result in A.
Since A register is one byte in size, the source operands must also be one byte. All
addition is done with the A register as the destination of the result.

ADD A, Rr Add A and register Rr put the sum in A


If there is a carry out of bit position 7, it is cleared to 0 otherwise
AC flag is set to 1 if there is a carry out of bit position 3, it is cleared otherwise
OV flag is set to 1 if there is a carry out of position 7 but none from D6 to D7
And if there is a carry from D6 to D7 and no carry out of D7.
e. g. ADD A, R4 Add A and register R4 put the sum in A

Some instructions include the carry flag as an additional source of a single bit that is
included in the operation at the least significant bit position.

ADDC A, #n Add the contents of A, the immediate number n and the C flag, put the
sum in A
C, AC and OV flags behave exactly as they do for the ADD commands.
e .g. MOV A, #1AH
ADDC A, #10H if C=1,A=2BH
ADDC is normally used to add a carry after the LSBY addition in a multi-byte process.
3) INC byte
This instruction adds 1 to the register or memory location specified by the operand.Cy is
not affected even if value FF is incremented to 00. It supports accumulator, register,
direct and register indirect addressing modes.

INC A Add a 1 to the register A


INC Rr Add a 1 to the register Rr
DEC Rr Subtract a 1 from the register R0
There are simple arithmetic operations involving adding or subtracting a binary 1 and a
number.
e.g. INC R0 Add a 1 to the register R0
DEC R0 Subtract a 1 from the register R0

4) JNC target
Jump if no carry. The instruction examines the CY flag and if it is zero it will jump to
target address.
e.g. JNC radd Jump relative address if the Carry flag is reset to 0.

5) DJNZ byte, target


Decrement and jump if not zero. In this instruction a byte is decremented and if result is
not zero, it will jump to the target address.
e.g. DJNZ Rr,radd
Decrement register Rr by 1 and jump to the relative address if the result is not 0

6) RET
Return from subroutine. This instruction is used to return from a subroutine previously
entered by instructions LCALL or ACALL. The top two bytes of the stack are popped
into program counter (PC) and program address at new location is executed. After
popping, stack contents, the stack pointer (SP) is decremented by 2.

Input: n 8 bit numbers stored in internal RAM location 40H onwards. First location
should contain value of n.
Output: Result of addition of n 8 bit numbers stored in R6 and R7.

Algorithm:

1) Take the count of numbers to be added into one of internal registers.


2) Initialize pointer to access internal memory to access numbers to be added.
3) Initialize accumulator with zero value for addition
4) Go on adding numbers in internal memory till counter becomes zero.
Decrement count with each addition
5) Store the result of addition in respective registers

Program (With comments):

Calculations:
Do calculation for addition of 5(n) numbers stored in internal memory.

Conclusion: Internal memory accesses are studied by performing addition of 8 bit


numbers stored in internal memory

FAQs.
1) What is the difference between the following two instructions in terms of
addressing mode and function performed?
MOV A, #46H
MOV A, 46H
2) What address is assigned to register A?
3) How to change register bank in 8051?

References:
1. Ayala,”The 8051 Micro Controller 3rd Edition”, IE
2. Mazidi M.Gillipse J. “The 8051 Microcontroller and Embedded Systems”, Pearson
Education, 2002, ISBN-81-7808-574-7

Assignment No.-10

Title: 16-bit x 8-bit multiplication


Aim: To write a program to multiply 16 bit number by 8 bit number and store the result
in internal memory location.

Objective: i) To learn internal memory access


ii) To perform 16 bit by 8 bit multiplication using 8 bit registers.

Theory:

16 bit x 8 bit Multiplication

Normal multiplication

Consider 25 x 16
Step1: First multiply by the least significant digit 25 x 6= 150
Here take 15 as a carry since it exceeds the number of digits in “6” i. e. 1
Keep 0 as the least significant digit of the answer.

Step 2: Now multiply 25 by the most significant digit 25 x 1= 25

Step 3: Now add the carry to this number 25+15=40


Therefore the answer becomes 400.

Now consider it in hex. Consider FFFF x FF


Step 1: FF x FF=FE01
Keep FE as carry and 01 as the lower byte of answer.

Step 2: FF x FF= FE01

Step 3: Add carry FE01 + FE= FEFF It is addition of a 16 bit number and an 8 bit
number. Therefore addition will take two steps if carry gets generated by addition of
lower byte.

Instructions used:

1) MOV Rr, #n Copy the 8 bit number n into register Rr of the current register
bank
For e.g. MOV R0, #40H Put 8-bit memory address in register R0
Where 40H is internal memory location
Here immediate addressing mode is used.

2) MOV A, @Rp Copy the contents of the address in Rp to A


MOV @Rp, A Copy the data in A to the address in Rp

Here indirect addressing mode is used. Any register R0 to R7 can be used to hold address
of the data. Here register R0 or R1 is often called a data pointer to hold address of one of
the data locations in RAM from address 00H to 7FH
For e.g. MOV A,@R0 Copy the contents of the address in R0 to the A register
MOV @R0, A Copy the data in A to internal memory address in R0

3) MOV A, Rr Copy data from register Rr to register A


MOV Rr, A Copy data from register A to register Rr.
Rr can be any register from R0 to R7
Here register addressing mode is used. A data MOV does not alter the contents of the
data source address. A copy of the data is made from source and moved to the destination
address. The contents of the destination are replaced by the source contents.
e. g. MOV R1, A Copy data from register A to register R1
MOV A, R1 Copy data from register R1 to register A

4) Incrementing and Decrementing


INC A Add a 1 to the register A
INC Rr Add a 1 to the register Rr
DEC Rr Subtract a 1 from the register R0
There are simple arithmetic operations involving adding or subtracting a binary 1 and a
number.
e.g. INC R0 Add a 1 to the register R0
DEC R0 Subtract a 1 from the register R0

5) Addition
All addition is done with the A register as the destination of the result.
ADD A, Rr Add A and register Rr put the sum in A
If there is a carry out of bit position 7, it is cleared to 0 otherwise
AC flag is set to 1 if there is a carry out of bit position 3, it is cleared otherwise
OV flag is set to 1 if there is a carry out of position 7.
e.g. ADD A, R4 Add A and register R4 put the sum in A

Some instructions include the carry flag as an additional source of a single bit that is
included in the operation at the least significant bit position.

ADDC A, #n Add the contents of A, the immediate number n and the C flag, put the
sum in A
C, AC and OV flags behave exactly as they do for the ADD commands.
e .g. MOV A, #1AH
ADDC A, #10H if C=1, A=2BH
ADDC is normally used to add a carry after the LSBY addition in a multi-byte process.

6) Multiplication
Multiplication operations use registers A and B as both source and destination addresses
for the operation. The unsigned number in register A is multiplied by the unsigned
number in register B as follows

MUL AB Multiply A by B; Put the low order byte of the product in A.


Put the high order byte in B
The OV flag will be set if A x B>FFh. It signals that the number is larger than 8 bits and
the programmer needs to inspect register B for the high order byte of the multiplication
operation. The carry flag is always cleared to 0.
e.g. MOV A, #7BH A=7BH
MOV 0F0H, #02H B=02H
MUL AB A=F6H and B=00H, OV=0
MOV B, #0FE B=FEH
MUL AB A=14H and B=F4H, OV=1

Input: 16 bit and 8 bit number stored in internal memory locations.


16 bit number=BBEEH
8 bit number=FFH

Memory Location Value Stored


40 BBH (Higher byte of 16 bit number)
41 EE H (Lower byte of 16 bit number)
42 FFH

Output: Result of 16 bit x 8 bit multiplication stored at internal memory locations from
50H onwards
BBEE x FF = BB3212

Memory Location Value Stored


50 BBH (First byte of result)
51 32H (Second byte of result)
52 12H (Third byte of result)

Algorithm:
Input is in 40H to 42H
Output is in internal memory 50H to 52H

1) Initialize pointer to internal memory and copy the memory location content (input)of
corresponding location to corresponding internal registers
2) Initialize memory pointer to internal memory to store the output
3) Load the lower byte of the 16 bit number into accumulator A and 8 bit number into
register B
4) Multiply them using instruction MUL AB
5) Store lower byte of product in internal memory
6) Store the higher byte of product in one of general purpose register
7) Get higher byte of 16 bit number into accumulator and 8 bit number into register B
8) Multiply them using instruction MUL AB.
9) Add lower byte of the product with higher byte of previous multiplication.
10) Store the result into internal memory
11) Add carry with the higher byte and store it into memory

Program (with comments):


Calculations:
16 bit number= BBEEH
8 bit number= FFH

Multiplication of BBEE x FF
Step 1: EE x FF= ED12H
Keep ED as carry and 12 as the lower byte of the answer.

Step 2: BB x FF=BA45H

Step 3: Add the carry BA45 + ED= BB32


Therefore the answer is BB3212

Conclusion: Internal memory accesses are studied by multiplying 16 bit number with 8
bit number

FAQs:
1) Give significance of MUL instruction.
2) How to check zero flag in 8051?
3) What is bit addressable area? How many bits are addressable? What is their
significance?

References:
1. Ayala,”The 8051 Micro Controller 3rd Edition”, IE
2. Mazidi M.Gillipse J. “The 8051 Microcontroller and Embedded Systems”, Pearson
Education, 2002, ISBN-81-7808-574-7

Assignment No.11

TITLE: Timer Programming

AIM:
Write assembly language program to generate a square wave of 2 KHz on any port
pin. Use Timer with interrupt for delay generation.

OBJECTIVE: 1. Understanding the Timers and the required SFRs.


2. Use of Timer to generate the time delays.
S/W & H/W USED: 1. Keil uVision2 Compiler / Assembler
2. Flash magic Software for downloading
3. 8051 Trainer kit.
4. CRO
THEORY:
TIME DELAY GENRATION:
Most used subroutine is one that generates a programmable time delay. Time
delays may be done by using software loops that essentially do nothing for some period
or by using hardware timers that count internal clock pulses. The key to writing this
program is to calculate the exact time each instruction will take at the clock frequency in
use. Following terms are very helpful to write a subroutine which generates desired time
delay.

T-state: T-state is defined as one subdivision of the operation performed in one clock
period. The terms T-state and clock period are often used synonymously.

Machine Cycle: Machine cycle in 8051 is defined as 12 oscillator periods. The 8051,
take one to four machine cycles to execute an instruction. To calculate the machine cycle
for the 8051, we take 1/12 of crystal frequency, and then take its inverse.
Assume crystal frequency of 11.0592 MHz
M/C frequency = 11.0592 MHz/12 = 921.6 KHz
Machine Cycle = 1/921.6 KHz = 1.085 us (microseconds)

Instruction Cycle: Instruction cycle is defined as the time required for completing the
execution of an instruction. One instruction cycle consists of one to four machine cycles.
e.g. 2 Machine cycles are required for instruction DJNZ R2, target to be executed. Then
instruction cycle is calculated as follows.
Instruction cycle = No. Machine cycles x Machine cycle period
= 2 x 1.085 us
= 2.17 us

Simple (single loop) Delay Subroutine


Label Mnemonics Machine cycles
Delay: MOV R3, #200 1
Here: DJNZ R3, Here 2
RET 2
 DJNZ instruction executed for 200 times.
 Here loop generates time delay = (200x2) x1.085us = 434 us.
 MOV and RET instruction are executed only once and they are called as overhead
of the delay subroutine.
 Overhead = (1+2) x1.085us = 3.255 us.
 Total Time delay = Loop delay + Overhead
= 434 us + 3.255 us = 437.255 us

Calculation for desired Time delay


 Suppose we want to generate the delay of 100us.
 Simple delay subroutine can generate the 100us delay since delay is less than
maximum delay (566 us) generated by subroutine.
Label Mnemonics Machine cycles
Delay: MOV R3, #YY 1
Here: DJNZ R3, Here 2
RET 2
 Find out the value of YY to get desired time delay.
 Time delay (Td) = Loop Delay + Overhead (as per above discussion)
 Loop delay = YY x 1.085 us, overhead = 3 x 1.085 us = 3.255 us
 Td = YY x 1.085 us + 3.255 us
 Therefore YY = (Td – 3.255us)/1.085us= (100us – 3.255us)/1.085us
 YY = 89.16 = (89)10 = 59H
 In similar manner we can generate the larger delay using nested loops.
 For larger delay, first calculate the count value for inner loop, then calculate count
value for outer loop considering delay generated by inner loop.

TIMER/ COUNTER IN 8051:
8051 has 2 timer/ counter. They can be used a timers to generate a time delay or
as counter to count events happening outside the microcontroller. Both Timer 0 and
Timer 1 are 16 bits wide. Since the 8051 has an 8-bit architecture, each 16-bit timer
register is accessed as two separate registers of low byte and high byte.
 Timer 0 can be accessed as –
o TL0 – Timer 0 lower byte
o TH0 – Timer 0 higher byte
 Timer 1 can be accessed as –
o TL1 - Timer 1 lower byte
o TH1 – Timer 1 higher byte
Both timer shares the Timer control (TCON) register, which controls the timer/
counter operation and Timer mode (TMOD) register, which is used to configure the
timer for different operating modes.

TMOD (Timer Mode Register):

 Both the timers used the same 8 bit register to set various timer operation
mode.
 TMOD is 8-bit register where lower 4 byte are set aside for timer 0 and
higher 4 bytes for timer 1. Since, it is not bit addressable; the
corresponding bit value is directly loaded into TMOD.
Gate:
 8051 has both hardware and software controls to start and stop the timers.
 By the means of software controlling instruction timers are used to control
to start timer or stop.

C/T:
 This bit in TMOD is used to determine whether timer is to be used as
delay generator or event counter.
o If C/T = 0 – used as timer
o If C/T = 1 – used as counter
M1 M0:
M1, M0 selects the timer mode.

M1 M0 Mode Operation
0 0 0 13 bit counter, 8 bit C/T with THX and
TLX as 5 bit Prescalar.
0 1 1 16 bit counter, 8 bit C/T with THX and
TLX cascaded with no Prescalar.
1 0 2 8 bit auto reload, THX hold the value
which is to be loaded into TLX after
each overflow.
1 1 3 Split timer mode.

TCON (Timer Control Register):

 Timer run control bits TR0 and TR1 and timer overflow flags TF0 and
TF1 are the part of 8 bit register called TCON.
 The upper 4 bits are used to store TR and TF flags of both timer- 0 and
timer 1 while the lower 4 bits are set aside for interrupt.
 Timer run control bit TR0/TR1 is used to start the corresponding timer /
counter.
 Timer overflow flag bit TF0/TF1 is set when corresponding timer/ counter
is overflowed i.e. count value FFFF h to 0000 h.

Different Modes of timer/ counter –


1. Mode 0 (13 bit timer/counter):
 Mode 0 is exactly like mode 1 except it is 13 bit timer.
 Hence it can hold the values from 0000H to 1FFFH in TL and TH.
 When timer rolls over from 1FFFH to 0000H, the overflow flag i.e. TFX is
set.

2. Mode 1 (16 bit Timer / counter):


 It is 16 bit timer. Hence allowed values from 0000H to FFFFH to be loaded in
TLX and THX.
 After the corresponding 16 bit value is loaded, the timer is started by setting
TRX flags.
 After starting, it counts up until it reaches the limit i.e. FFFFH. When it rolls
over from FFFFH to 0000H, it sets timer overflow flag i.e. TFX flag.
 After the rolling over process, the operation in mode 1 can be repeated by
loading the initial value in TLX & THX and clearing TFX bit.

Figure 3.1: Timer/ Counter in Mode 0 and Mode 1

3. Mode 2 (8 bit auto reload):


 It is 8 bit timer. Hence it allows only values from 00H to FFH to be loaded in
THX.
 When THX is loaded into 8 bit value, it sends a copy of it to corresponding
TLX. Then timer must be started which is done by SETB TR1 for T1.
 After rolling over of TLX from FFH to 00H, overflow flag for corresponding
timer i.e. TFX is set. TLX auto loaded by value present in THX.

Figure 3.2: Timer/ Counter in Mode 2

4. Mode 3 (Split timer mode):


 In mode 3, timer0 worked as split timer i.e. two independent timer.
 TL0 uses the TR0 and TF0 bits of timer 0.
 TH0 uses the TR1 and TF1 bits of timer 1.

Figure 3.3: Timer/ Counter in Mode 3

TIME DELAY GENERATION USING TIMER:


Mode 1 and Mode 2 are widely used for most of the applications. Mode 1 is used
for time delay generation and mode 2 is used to generate the baud rate in serial
communication.
The following steps are taken to generate a time delay using the mode 1 and polling
method.
i. Load the TMOD value indicating which timer is to be used and timer mode
1 is selected.
ii. Load the registers TL and TH with initial count values. Delay generated is
Depends upon the initial count value.
iii. Start the timer. (SETB TR0 or SETB TR1)
iv. Keep the monitoring the timer flag (TF) with the “JNB TF0, target” or “JNB
TF1, target” instruction.
v. Get out of the loop when TF becomes high.
vi. Stop the timer. (CLR TR0 or CLR TR1)
vii. Clear the TF flag for the next round. (CLR TF0 or CLR TF1)
viii. Go back to the step 2 to load TH and TL values.

The size of the time delay depends on two factors, (a) the crystal frequency and (b) the
timer’s 16-bit register in mode 1. The largest delay is achieved by the making both TH
and TL zero.
Formula for delay calculations using mode 1 of the timer for crystal frequency of XTAL
= 11.0592 MHz, (TH, TL) = (NNNNN)10 is as follows.

Time Delay (Td) = (65536 - NNNNN) x 1.085 us.


Therefore Maximum delay = (65536 – 0000) x 1.085 us = 71 ms.
Finding the Values to be loaded into timer for desired delay
Assume the 11.0592 MHz as crystal frequency for 8051.
 Divide the desired time delay by 1.085us. ( n = Td/1.085us)
 Perform 65536 – n. where n is the decimal value from step 1.
 Convert the result of step 2 to hexadecimal, where yyxx is the initial hex
value to be loaded into the timer’s registers.
 Set TL = xx and TH = yy.

Calculations:
Frequency = 2 KHz
Machine Cycle = 1.085 us (microseconds)
Time period = TP = 1/2x103 = 0.5 ms
Required duty cycle is 50%
Therefore, Ton = Toff = 1/TP = 0.25 ms
Desired time delay is TD = 0.25 ms
Divide TD by 1.085x10-6 = n = 0.25x10-3/1.085x10-6 = 230
Subtract n from 65536 = 65536 – 230 = 65306
Convert above decimal value in to Hex value = FF1Ah
Load this value into Timer Register. (TH = FFh , TL = 1Ah)
ALGORITHM: To generate the 2 KHz square wave on port pin
A. Main Program
1. Load the value “10h” in TMOD register indicating Timer-1 is to be used and
timer mode 1 is selected.
2. Load the registers TL and TH with initial count values i.e. FF1Ah.
(TH = FFh, TL = 1Ah)
3. Enable the Timer-1 interrupt by loading the value “88h” in IE register.
4. Start the timer by setting TR1 bit in TCON register.
5. Halt the program.
B. ISR Routine
1. Complement the port bit on which square wave is to be monitored.
2. Reload the registers TL and TH with initial count values i.e. FF1Ah.
(TH = FFh, TL = 1Ah)
3. Return from ISR.
4.

PROGRAM WITH COMMENTS:

CONCLUSION: Timer operations and time delay generation in 8051 are studied

FAQ’s:

REFERENCES:
1. The 8051 Microcontroller & Embedded systems
- M. Mazidi
2. The 8051 Microcontroller Architecture, Programming & Applications
- Kenneth Ayala

You might also like