Professional Documents
Culture Documents
PROBLEM DEFINITION: A. B. C. D. Write a program to add two 16-bit numbers. Write a program to convert temperature in degree Celsius to degree Fahrenheit. Write a program to convert temperature in degree Fahrenheit to degree Celsius. Write a program to add n 8 bit numbers found in internal RAM locations 40H onwards & store the result in R6 (LSB) & R7 (MSB). Write a program to add BCD 7795H to 4548H and save the BCD result in RAM memory locations starting at 40H. : Keil uVision2 Compiler / Assembler
E.
A microcontroller has a CPU (a microprocessor) in addition to a fixed amount of ROM, RAM, I/O ports and a timer etc. all on a single chip. The 8-bit microcontrollers were developed by Intel, Motorola, Zilog, Philips, Microchip etc.
8051 Microcontroller:
The 8051 is the first microcontroller of the MCS-51 family, introduced by Intel Corporation at the end of the 1980s. The 8051 family with its many enhanced members enjoys the largest market share, estimated to be about 40% among the various microcontroller architectures. The salient features of the 8051 microcontroller are given below. I. 8 bit CPU with resisters A and B. II. On-chip clock oscillator. III. 4Kbytes on-chip Internal ROM (program memory) IV. Internal ROM of 128 bytes A. 4 register banks each containing 8 resisters B. 16 bytes which may be addressed at the bit level
Users Lab Manual (Experiments) C. 80 bytes of general purpose data memory 32 Input/output pins arranged as four 8- bit ports: P0 to P3 Two 16 bits timer/counters i.e. T0 & T1 Full duplex serial data receiver/transmitter (SBUF) 16 bit PC (program counter) and DPTR (data pointer). 8 bit PSW (program status word). 8 bit SP (stack pointer). Control resisters (like TCON, TMOD, SCON, PCON, IP 64-kbytes of program memory address space 64-kbytes of data memory address space 16-bit address bus multiplexed with port 0 and port 2; 8-bit data bus multiplexed with port 0. Five-vector interrupt structure with two priority levels.
Internal memory organization:Microcontroller 8085 has mainly internal RAM and ROM memory. Internal Memory organized in 8051 is such that the data memory and the program code memory are entirely different memory entities. However additional memory can be added externally. a. Internal ROM 8051 has 4 KB of Internal ROM. Programmer code contained in internal ROM occupies the address space 0000H to 0FFFH (i.e. 12bits). Program Counter (PC) is ordinarily used to address program code bytes from address 0000H to 0FFFH. Program addresses higher than 0FFFH which exceed the internal ROM capacity will cause 8051 to automatically fetch byte from the external memory.
Users Lab Manual (Experiments) Code bytes can also be fetched exclusively from the external memory addresses 0000H to FFFFH, by connecting external access pin EA on DIP to ground. b. Internal RAM 8051 has 128 bytes internal RAM which is distributed in four register banks, bit addressable memory, scratch pad memory. A total 32 bytes from address locations 00H to 1FH are set aside for register banks and the stack. These 32 bytes are divided into 4 banks of registers in which each bank has 8 resisters, R0 R7. A bit addressable area of 16 bytes occupies RAM address 20H to 2FH forming 128 addressable bits. A total of 80 bytes from locations 30H to 7FH are used for read and write storage or what is normally called a scratch pad. These 80 locations of RAM are widely used for the purpose of storing data and parameters by programmers.
3. Direct Addressing Mode: o All 128 bytes of internal RAM and SFR may be directly addressable using single byte address. o Internal RAM uses addresses from 00h to 7FH to each address byte. o This addressing mode consists of direct address and SFR register addresses. Mnemonic Operations MOV A, 80h Copy the data from P0 to register A MOV R0, 12h Copy the data from RAM loc to register R0
Users Lab Manual (Experiments) MOV 5ch, A MOV 0A8h, 77h Copy the content of A to address 5ch Copy the data from RAM loc 77h to IE reg.
4. Indirect Addressing Mode:o The indirect addressing mode uses register R1, R0 and DPTR to hold the address that will be finally used in the data move, the register itself is not the address but rather the number in register. Indirect addressing cannot be used to refer to SFR registers. Both R0 and R1 can hold 8-bit address and DPTR can hold 16-bit address. Mnemonic MOV @Rp, #nn MOV @Rp, add MOV @Rp, A MOV A, @Rp MOV add, @Rp Operations Copy immediate data to the address in Rp. Copy the memory contents to the addr. in Rp. Copy the content of A to address in Rp. Copy the contents of address in Rp to A. Copy the contents of the addr. in Rp to mem loc.
REFERENCES : 1. The 8051 Microcontroller & Embedded systems - M. Mazidi 2. The 8051 Microcontroller Architecture, Programming Applications - Kenneth Ayala
&
1B) Write a program to convert temperature in degree Celsius to degree Fahrenheit. Assumptions: [R0] holds the data 0C (in Hex format) [R1] Holds the result oF (in Hex format)
This program will for only temperature range 00 C to 830 C, since it will not consider the carry. Also result is 30 F less due to fractions. ORG 0000H SJMP MAIN ; Skip the interrupt vector ORG 0030H MAIN:MOV A, R0 ; Move data in to accumulator MOV B, #05 DIV AB ; Divide data with 09. MOV B, #09 MUL AB ; Multiply 05 with result in last step MOV R1,#32 ; Add 32 to the result in last step ADD A, R1 MOV R1, A ; Move result in register R1 HERE:SJMP HERE END
1C) Write a program to convert temperature in degree Fahrenheit to degree Celsius. Assumptions: [R0] holds the data oF (in Hex format) [R1] Holds the result 0C (in Hex format) This program will for only temperature range 00 F to 830 F, since it will not consider the carry.
ORG 0000H SJMP MAIN ORG 0030H MOV A, R0 MOV R1,#32 SUBB A, R1 MOV B, #05 MUL AB MOV B, #09 DIV AB MOV R1, A SJMP HERE END ; Skip the interrupt vector ; Move data in to accumulator ; Subtract 32 from data ; Multiply 05 with result in last step ; Divide last step result with 09. ; Move result in register R1.
MAIN:
HERE:
1D) Write a program to add n 8 bit numbers found in internal RAM locations 40H onwards & store the result in R6 (LSB) & R7 (MSB).
ORG 0000H SJMP START ORG MOV MOV MOV MOV MOV 0030H R1,#40H R2,#0AH A,#00H R4,00H R5,00H
START:
; ; ; ; ; ; ; ; ; ;
Starting address of memory locations counter value Clear the accumulator to store the result clear the R4 to store the carry clear the R5 to store the result Add the contents of memory loc. To A. check for carry increment for carry INCREMENT POINTER decrement the counter and jump if not
NEXT:
zero. MOV R5, A MOV R1, #50H result MOV @R1, R4 INC R1 MOV @R1, R5 HERE: SJMP HERE END ; store carry to memory locations : Increment memory pointer ; Store the result ; Store the result in register R5 ; Initialize the memory pointer to store
1E) Write a program to add BCD 7795H to 4548H and save the BCD result in RAM memory locations starting at 40H.
ORG 0000H SJMP START ORG 0030H START: MOV A,#95H ADD A,#48H accumulator DA A MOV 40H,A MOV A,#77H ADDC A,#45H accumulator DA A MOV 41H,A CLR A RLC A MOV 42H, A HERE: SJMP HERE END ; skip the interrupt vector ; LSB of first no. in to accumulator ; add LSB of second no.
to
; Decimal adjust ; store result at memory location ; MSB of first no. in to accumulator ; add MSB of second no. to ; Decimal adjust ;store result at memory location ; Check for carry from MSB.
; Skip the interrupt vector table ; START AT LOCATION 0030H ;LSB OF NO.1 ;MSB OF NO.1 ;LSB OF NO.2 ;MSB OF NO.2
EXPT. NO.: 2
TITLE
PROBLEM DEFINITION: A. B. C. D. E. Write a program that finds the number of zeros in an 8-bit data item. Write a program to arrange an array in ascending/descending order. Write a program using lookup table, using the DPTR as the base that finds the square of the number in A. Write a program to copy a block of 10 bytes of data from Internal RAM locations 30H to Internal RAM locations 60H. Write a program to copy a block of 10 bytes of data from External RAM locations 0200H to Internal RAM locations 40H. : Keil uVision2 Compiler / Assembler
Users Lab Manual (Experiments) 1. Data transfer instructions: Data is stored at a source address and moved to a destination address. The following five types of opcodes are used to move data. a. MOV dst, src b. MOVX dst, src c. MOVC d. XCH e. PUSH and POP The MOV opcodes involve the data transfers within the 8051 memory. This memory divided into the following four distinct physical parts. i. Internal RAM ii. Internal special function registers iii. External RAM iv. Internal and External ROM Data transfer operation Move the contents of accumulator A to register Rn Move the contents of register Rn to accumulator A. Move an immediate 8-bit data to i. Accumulator ii. Register Rn iii. Direct memory location iv. Indirect memory location v. Data pointer (DPTR) register Move the contents of a memory location to Accumulator A and vice versa using direct addressing Move the contents of a memory location to Accumulator A and vice versa using indirect addressing Move the contents of a memory location to Register and vice versa using direct addressing Move the contents of a memory location to another memory locations using direct addressing and indirect addressing Move the contents of an external memory location pointed by Rp to Accumulator A and vice versa. Move the contents of an external memory location pointed by DPTR to Accumulator A and vice versa. Move the contents of program memory to Accumulator A. Instruction MOV Rn, A MOV A, Rn MOV MOV MOV MOV MOV MOV MOV A, #data Rn, #data direct, #data @Rp, #data DPTR, #16bit data A, direct direct, A
MOV A, @Rp MOV @Rp, A MOV Rn, direct MOV direct, Rn MOV direct1, direct2 MOV direct, @Rp MOV @Rp, direct MOVX A, @Rp MOVX @Rp, A MOVX A, @dptr MOVX @dptr, A MOVC A, @A+DPTR MOVC A, @A+PC
Users Lab Manual (Experiments) XCH A, Rn XCH A, @Rp XCH A, Direct Exchange the digits: exchanges the low order nibble XCHD A, @Ri of the accumulator A with that of the internal memory location pointed by Rp. Push and Pop Instructions PUSH direct POP direct 2. Arithmetic instructions: 8051 has powerful instructions in the arithmetic group compared to other microcontrollers. It can perform addition, subtraction, multiplication and division operations on 8-bit numbers. a. Addition: All addition is done with A as destination address. Some instructions may be use carry flag as an additional source of a single bit that is included in the operation at the LSB position. AC flag is set when a carry is generated from lower nibble to higher nibble i.e. from D3 to D4. OV flag set if a carry is out of MSB bit i.e. D7. All four addressing modes can be used for subtraction. Addition operation Add the contents of Accumulator A with immediate data without / with carry and store the result in A Add the contents of Accumulator A with register Rn without / with carry and store the result in A Add the contents of Accumulator A with contents of memory location without / with carry and store the result in A using direct addressing. Add the contents of Accumulator A with contents of memory location without / with carry and store the result in A using indirect addressing. Instruction ADD A, #data ADDC A, #data ADD A, Rn ADDC A, Rn ADD A, direct ADDC A, direct ADD A, @Rp ADDC A, @Rp Exchange Accumulator A with byte variable
b. Subtraction: The 8051 has commands to program subtraction of two signed or unsigned numbers. Register A is a destination address of all types of subtraction instruction. All four addressing modes can be used for subtraction. The carry flag is treated as borrow and subtract carry flag from the resultant. S2N Systems, Pune. Cell No. 9011097672
Users Lab Manual (Experiments) Carry Flag, Auxiliary carry flag, Overflow flags are affected. Instruction SUBB A, #data SUBB A, Rn
Subtraction operation Subtract immediate data and contents of carry flag from Accumulator A and store the result in A Subtract contents of register Rn and contents of carry flag from Accumulator A and store the result in A. Subtract contents of memory location and contents of carry flag from Accumulator A and store the result in A using direct addressing. Subtract contents of memory location and contents of carry flag from Accumulator A and store the result in A using indirect addressing.
SUBB A, direct
SUBB A, @Rp
c. Multiplication: Instruction: MUL AB Only two registers are used A & B. Multiplies the unsigned 8-bit integer in the register A and register B. After multiplication lower byte is put into A and higher order in B. The carry flag is always cleared to 0 after multiplication. The overflow flag will be set if product is greater than FF. In this high order byte is stored in register B. d. Division: Instruction: DIV AB Only registers A & B are used. Divides the unsigned 8-bit integer in the accumulator A by the unsigned 8-bit integer in register B. The quotient is stored in the Accumulator A and remainder is stored in register B. OV flag is set to 0 unless B holds the 00h before division, then OV flag is set to 1 to show division by 0. d. Increment instructions: Instruction: INC <Byte> Increments the indicated variable by 1. Flags are not affected. All addressing modes are supported. Increment operation Increments the contents Accumulator A by 1. Increments the contents of register Rn by 1 Instruction INC A INC Rn
Users Lab Manual (Experiments) Increments the contents of memory location by 1 INC direct using direct addressing. Increments the contents of memory location by 1 INC @Rp using indirect addressing. Increments the contents of DPTR by 1 INC DPTR d. Decrement instructions: Instruction: DEC <Byte> Decrements the indicated variable by 1. Flags are not affected. All addressing modes are supported. Decrement operation Instruction Decrements the contents Accumulator A by 1. DEC A Decrements the contents of register Rn by 1 DEC Rn Decrements the contents of memory location by 1 DEC direct using direct addressing. Decrements the contents of memory location by 1 DEC @Rp using indirect addressing. Decrements the contents of DPTR by 1 DEC DPTR d. Decimal Adjustment after addition: Instruction: DA A Adjusts the sum of two packed BCD numbers found in Accumulator A; leave the adjusted number in accumulator A.
3. Logical instructions: Logical instructions are very useful in input / output operations. They can perform the various operations such as AND, OR, EXOR, Complement, swap and rotate. a. AND operation (ANL) Bitwise logically AND the contents of destination and source. Flags are not affected. Logical AND operation Instruction AND the immediate data with contents of ANL A, #data Accumulator A or with contents of memory locations ANL direct, #data using direct addressing. AND the contents Accumulator A with contents of ANL A, Rn register Rn and store the result in A. AND the contents Accumulator A with the contents ANL A, direct of memory location using direct addressing. ANL direct, A AND the contents Accumulator A with the contents ANL A, @Rp
Users Lab Manual (Experiments) of memory location using indirect addressing. b. OR operation (ORL) Bitwise logically OR the contents of destination and source. Flags are not affected. Logical OR operation Instruction OR the immediate data with contents of ORL A, #data Accumulator A or with contents of memory locations ORL direct, #data using direct addressing. OR the contents Accumulator A with contents of ORL A, Rn register Rn and store the result in A. OR the contents Accumulator A with the contents of ORL A, direct memory location using direct addressing. ORL direct, A OR the contents Accumulator A with the contents of ORL A, @Rp memory location using indirect addressing. c. EX-OR operation (XRL) Bitwise logically OR the contents of destination and source. Flags are not affected. Logical EX-OR operation EX-OR the immediate data with contents of Accumulator A or with contents of memory locations using direct addressing. EX-OR the contents Accumulator A with contents of register Rn and store the result in A. EX-OR the contents Accumulator A with the contents of memory location using direct addressing. EX-OR the contents Accumulator A with the contents of memory location using indirect addressing. Instruction XRL A, #data XRL direct, #data XRL A, Rn XRL A, direct XRL direct, A XRL A, @Rp
d. Clear, Complement and swap the accumulator CPL A: This will complement all the bits of accumulator. CLR A: This instruction will clear all the accumulator bits to 0. SWAP A: This instruction interchanges the low and high order nibbles of the accumulator A. e. Rotate Instructions Rotate the only contents of accumulator A by 1-bit. Carry flag is affected by the rotate instructions
Rotate operation Rotate the Accumulator A one bit position left. Rotate the Accumulator A through carry flag position to the left. Rotate the Accumulator A one bit position right. Rotate the Accumulator A through carry flag position to the right.
4. Branch (Jump) instructions: When jump instruction is executed by the 8051, a jump occurs, which can be a forward or a backward jump. The 8051 supports two types of jump instructions. a) Unconditional jump instructions b) Conditional jump instructions a. Bit Jumps b. Byte Jumps a. Unconditional jump instructions Unconditional jump do not test any condition to determine the jump. The execution of this instruction always results in a branch. The destination address is provided as a part of the instruction. Unconditional jump instructions are used to jump any location in the memory. Unconditional Jump operation Jump to absolute long range 16-bit address (0000h to FFFFh). No PSW flags are affected. Jump to absolute short range 11-bit address (0000 07FFH). No flags are affected. Jump to the relative 8-bit address (00-FFH). No PSW flags are affected. Jump to the address formed by adding A to the DPTR. Instruction LJMP LADD AJMP SADD SJMP RADD JMP @A+DPTR
b. Conditional jump instructions Jumps operate by testing for conditions that are specified in the jump mnemonic.
Users Lab Manual (Experiments) If the condition is true, then the jump is taken i.e. the PC is altered to the address that is part of the jump instructions. If the condition is false, then the instruction immediately following the jump instruction is executed. There are two types conditional jump instructions o Bit jumps: operates according to the status of the Carry flag or the status of any bit addressable location. o Byte jumps: test the bytes of data in contrast bit test. Instruction JC RADD JNC RADD JB bit, radd JNB bit, radd JBC bit, radd
Conditional Bit Jump operation Jump relative if the carry flag is set to 1. Jump relative if the carry flag is reset to 0. Jump relative if the addressable bit is set to 1. Jump relative if the addressable bit is reset to 0. Jump relative if the addressable bit is set to 1 and clear the addressable bit to 0 after jump. Conditional Byte Jump operation Jump relative if the accumulator contents are 0. Jump relative if the accumulator contents are not 0. Decrement the register Rn by 1 and jump to the relative address if the result is not 0. Decrement the direct address by 1 and jump to the relative address if the result is not 0. Compare the contents of the register A with the contents of the direct address; if they are not equal then jump to the relative address. Compare the contents of the register A with the immediate data; if they are not equal then jump to the relative address. Compare the contents of the register Rn with the immediate data; if they are not equal then jump to the relative address. Compare the contents of memory locations pointed by Rp with the immediate data; if they are not equal then jump to the relative address.
Instruction JZ RADD JNZ RADD DJNZ Rn, radd DJNZ direct, radd CJNE A, direct, radd
Figure 2.1: Jump Instruction Ranges 5. Bit Manipulation instructions: The 8051 supports a single bit operation. The internal RAM conatins 128 addressable bits (20H to 2FH) 00 to 7FH. SFR supports 128 addressable bits and all the I/O ports are bit addressable. Each I/O line can be treated as a separate single bit port. The 8051 provides bit manipulation instruction to perform operations such as AND, OR, SET, CLEAR, Complement and also conditional bit manipulation jump instruction. Conditional bit manipulation jump instructions are discussed under the jump instructions. The bit manipulation instructions operate on any addressable RAM or SFR bit. The carry flag (CF) in the PSW register is the destination for most of the op-codes because the flag can be tested and the program flow changed using jump instructions. Note that in bit manipulation instruction no flags, other than carry flag, are affected, unless the flag is an addressed bit. Bit level operation Instruction S2N Systems, Pune. Cell No. 9011097672
Users Lab Manual (Experiments) AND carry and addressed bit; put the result in CF AND carry and the complement of the addressed bit; put the result in CF; the addressed bit is not altered. OR carry and addressed bit; put the result in CF OR carry and the complement of the addressed bit; put the result in CF; the addressed bit is not altered. Complement the carry flag Complement the addressed bit Clear the carry flag to 0 Clear the addressed bit to 0 Set the carry flag to 1 Set the addressed bit to 1 Copy the addressed bit to carry flag Copy the carry flag to addressed bit REFERENCES : ANL C, bit ANL C, /bit
CPL C CPL bit CLR C CLR bit SETB C SETB bit MOV C, bit MOV bit, C
1. The 8051 Microcontroller & Embedded systems - M. Mazidi 2. The 8051 Microcontroller Architecture, Programming & Applications - Kenneth Ayala
2A) Write a program that finds the number of zeros in an 8-bit data item.
ORG 0000H SJMP MAIN ORG MOV MOV MOV 0030H A, 40H R5, #08H R6, #00H ; skip the interrupt vector table
MAIN:
; load regi. A with direct memory address ; load R5 with count value ; clear the Regi. R6 to store the result ; ; ; ; Rotate the Accumulator thru carry to right branch if bit is not zero increment if bit is zero. decrement counter and if not zero
UP:
SKIP: HERE:
2C) Write a program using lookup table, using the DPTR as the base that finds the square of the number in A.
ORG 0000H SJMP MAIN ORG 0030 MAIN: MOV A, 30H MOV DPTR,#0100H MOVC A, @A+DPTR MOV 31H, A 31H HERE: SJMP HERE END
; ; ; ;
get the no. from direct memory addr. 30H. initialize DPTE with lookup table address get the square of no from lookup table store the result at direct memory addr.
ORG 0100H ; look table consists of square of numbers SQUARE: DB 0,1,4,9,16,25,36,49,64,81,100 END
2B) Write a program to arrange an array in ascending/descending order. Assumptions: Memory Location (31H) : No. of bytes to sort Memory location (32H and onwards) : Bytes to be sorted
ORG 0000H LJMP START ORG 0030H MOV R3, 31H DEC R3 CLR A MOV R1,31H ; Skip the interrupt vector table ; initialize the outer counter (no. of passes)
START:
BACK0: comparing)
initialize
the
outer
counter
for
BACK1:
NEXT1: swapping
DEC R1 MOV R0,#32H ; initialize the memory pointer MOV 05H,@R0 ; move data to direct memory address 05h INC R0 ; increment memory pointer MOV A,@R0 ; move next to accumulator CJNE A,05H,NEXT1 ; compare the two bytes JNC AHEAD1 ; jump if [A] < [05H]; otherwise do MOV A,05H MOV 05H,@R0 MOV @R0,A DEC R0 MOV @R0,05H INC R0 DJNZ R1,BACK1 DJNZ R3,BACK0 SJMP EXIT END ; swapping data between [A], [05]
AHEAD1:
; increment memory pointer ; decrement inner counter & jump if not zero. ; decrement outer counter & jump if not zero.
EXIT:
NOTE: For descending order use instruction JC AHEAD1 instead of JNC AHEAD1.
2D) Write a program to copy a block of 10 bytes of data from Internal RAM locations 30H to Internal RAM locations 60H. Assumptions: Memory Location (30H onwards) : Source data address Memory location (60H onwards) : Destination data address ORG 0000H
SJMP START ORG 0030H MOV R0, #30H MOV R1, #60H MOV B, #0AH MOV A,@R0 MOV @R1, A INC R0 INC R1 DJNZ B, BACK SJMP HERE END ; Skip the interrupt vector ; initialize the memory pointer with source ;Initialize the memory pointer with destn ; Counter ; Move source contents to accumulator ; Move accumulator contents to destination ; Increment the source memory pointer ; Increment the destination memory pointer ; decrement the counter & jump if not zero.
START:
BACK:
HERE:
2E) Write a program to copy a block of 10 bytes of data from External RAM locations 0200H to Internal RAM locations 40H. Assumptions:
Memory Location (40H onwards) : Destination Internal data addr. Memory location (0200H onwards) : Source external data address ORG 0000H SJMP START ; Skip the interrupt vector ORG 0030H START: MOV DPTR, #0200H ; initialize DPTR with source address MOV R1, #40H ;Initialize the memory pointer with destn MOV B, #0AH ; Counter BACK: MOVX A,@DPTR ; Move source contents to accumulator MOV @R1, A ; Move accumulator contents to destination INC DPTR ; Increment the source memory pointer INC R1 ; Increment the destination memory pointer DJNZ B, BACK ; decrement the counter & jump if not zero. HERE: SJMP HERE END
EXPT. NO. : 3
PROBLEM DEFINITION: A. Write a counter program to count continuously from 00 to 99h in BCD with a delay of 750ms between each count. Display the count at any output port (Use looping for delay and show delay calculation). Use simulator to show the result. Write a program to generate a square wave of 50 Hz on the pin P2.4. (Use timer for delay generation). Use simulator to show the result. Keil uVision2 Compiler / Assembler
B.
A subroutine is a program that may be used many times in the execution of a larger program. This makes a program more structured in addition to saving memory space. Subroutines are usually handled by special instructions like CALL, RET. The following sequences of events are occurred for subroutines. i. When CALL instruction is executed, the return address of the next instruction after the call instruction is found in the PC. ii. Return address bytes are pushed on the stack. iii. The stack pointer is incremented for each push on the stack. iv. The subroutine address is placed in the program counter and subroutine is executed. v. A RET instruction is encountered at the end of the subroutine. vi. Two pop operations restore the return address to the PC from the stack area in internal RAM. vii. The stack pointer is decremented for each address byte pop.
Users Lab Manual (Experiments) Subroutine instructions 1. LCALL addr16: Long call instruction is used to call subroutines located anywhere within the 64k-byte address space of the 8051.This is the 3 byte instruction. The instruction saves the next instruction address on the stack and PC is loaded with the 16bit address of subroutine specified in instruction. 2. ACALL addr11: Absolute call is 2-byte instruction. The target address of the subroutine must be within 2Kbytes because only 11 bits of the 2 bytes are used for the address. 3. RET (return from subroutine): Return instruction is the last instruction of any subroutine to return to main program. RET instruction pops the stack and contents of the stack are loaded in PC. 4. RETI (return from interrupt): RETI instruction is the last instruction of any interrupt service routine to return to main program. It is similar to RET instruction, only difference is RETI also clears the TF0, TF1, IE0, IE1.
Users Lab Manual (Experiments) 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 Delay: Here: Mnemonics MOV R3, #200 DJNZ R3, Here RET Machine cycles 1 2 2
The Here loop delay = [(1+1+2) x 250] x 1.085us = 1085 us The again loop repeats the here loop for 200 times. Again loop delay = 200 x 1085 us = 217000 Overhead = (3 x200) x 1.085 us = 651 us Total delay = 217000 + 651 us = 217.651 ms.
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.
Users Lab Manual (Experiments) 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 0 0 M0 0 1 Mode 0 1 Operation 13 bit counter, 8 bit C/T with THX and TLX as 5 bit Prescalar. 16 bit counter, 8 bit C/T with THX and TLX cascaded with no Prescalar. 8 bit auto reload, THX hold the value which is to be loaded into TLX after each overflow. Split timer mode. S2N Systems, Pune. Cell No. 9011097672
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.
Users Lab Manual (Experiments) 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 timers registers. Set TL = xx and TH = yy.
REFERENCES : 1. The 8051 Microcontroller & Embedded systems - M. Mazidi 2. The 8051 Microcontroller Architecture, Programming Applications - Kenneth Ayala
&
3A) Write a counter program to count continuously from 00 to 99h in BCD with a delay of 750ms between each count. Display the count at any output port (Use looping for delay and show delay calculation). Use simulator to show the result.
ORG 0000H SJMP START ; Skip the interrupt vector ORG 0030H START: CLR A ; clear the accumulator BACK: MOV P2, A ; move the value on PORT 2 ADD A, #01 ; Increment counter by adding 1 DA A ; Decimal adjust to make BCD. ACALL DEL_750ms ; call delay HERE: SJMP BACK DEL_750ms: MOV R1, #15 ; generates delay of 750ms LOOP1: MOV R2, #100 ; generates delay of 50ms LOOP2: MOV R3, #229 ; generates delay of 500us LOOP3: DJNZ R3, LOOP3 DJNZ R2, LOOP2 DJNZ R1, LOOP1 RET ; return to main program END
3B) Write a program to generate a square wave of 50 Hz on the pin P2.4. (Use timer for delay generation). Use simulator to show the result.
ORG 0000H LJMP START ; SKIP THE INTERRUPT VECTOR TABLE ORG 0030H MOV TMOD, #10H ; SELECT TIMER 1 MODE 1 MOV TH1, #0DCH ; LOAD COUNT TO GET REQD. FREQ MOV TL1, #00H SETB TR1 ; START TIMER JNB TF1, LOOP ; CHECK IF OVERFLOW HAS OCCURED CPL P2.4 ; COMPLEMENT P2.4 CLR TF1 ; CLEAR TIMER OVERFLOW FLAG CLR TR1 ; STOP TIMER SJMP BACK END
START: BACK:
LOOP:
PROBLEM DEFINITION: A. Write a program in which falling edge of pulse is detected by interrupt port pin P3.3 (INT1). In response to this LED, which is connected to port P1.3, is turned on it stay on for 50ms and then turned off. Write a program to interface LED to P2.0 and toggle it after every 20ms. (Use Timer for delay and interrupts) Write a program to interface LEDs to 8051 so that a rolling display is observed on the LEDs connected to port P1 (Use Timer for delay). 1. Keil uVision2 Compiler / Assembler 2. Flashmagic Software for downloading 3. 8051 Trainer kit with LED array
B. C.
THEORY:
INTERRUPTS: Whenever any peripheral device needs the 8051 service, it notifies the microcontroller by sending interrupt signal. Upon receiving interrupt signal, microcontroller interrupt whatever it is doing and gives it service to the device. Program associated with the interrupt is called Interrupt Service Routine (ISR). Advantage of using interrupts is that the microcontroller can serve many devices (not all at the same time) Each device can get the attention of the microcontroller based on the priority assigned to the device. The polling method cannot assign priority since it checks all devices in a round robin fashion. Also by polling method, microcontrollers time wastage occurs as it also checks devices which dont need the service. Interrupt service routine (ISR): when peripheral devices activate an interrupt signal, the processor branches to a program called interrupt
Users Lab Manual (Experiments) service routine (ISR). The program is written by the user for performing tasks that the interrupting device wants the processor to execute. Interrupt Vector Table (IVT): The term interrupt vector refers to starting address of the ISR. The processor needs to determine starting address of the ISR before it can provide service. The group of memory locations set aside to hold the addresses of ISRs is called interrupt vector table. the the the the
The steps in executing an interrupts: Microcontroller finishes the instruction that it is executing and saves the address of the next instruction (PC) on the stack. It saves the current status of all interrupt internally (i.e. not on stack). It jumps to fixed location in memory called interrupt vector table that holds the address of ISR. The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it. Microcontroller executes ISR until it executes the last instruction of ISR i.e. RETI. Upon executing RETI, microcontroller returns to the address where it was interrupted. It gets the address by popping the 1st two bytes of the stack into PC and then further starts execution. 8051 interrupt structure: In reality, only five interrupts are available to the user in the 8051, but many manufacturers datasheets state that there are six interrupts since they include reset. The six interrupts in the 8051 are allocated as follows. 1. Reset: When the reset is activated, the 8051 will reset, terminate the all activities and set the all SFR with default values; then jumps to address location 0000h. 2. Two interrupts are set aside for external hardware interrupts (INT0 & INT1). These external interrupts are also referred to as EX1 and EX2. 3. Two interrupts are set aside for the timers: one for timer 0 (TF0) and for timer 1 (TF1). 4. Serial communication has a single interrupt that belongs to both receive and transmit. No. Interrupts ROM location (IVT) Pin number Flag clearing 1 Reset 0000 9 Auto 2 INT0 0003 P3.2 (12) Auto 3 TF0 000B Auto 4 INT1 0013 P3.3 (13) Auto 5 TF1 001B Auto S2N Systems, Pune. Cell No. 9011097672
The above table shows that a limited number of bytes are set aside for each interrupt. Only 8-bytes are reserved for ISR of the each interrupt. If the service routine for a given interrupt is short enough to fit in the memory space allocated to it, it is placed in the vector table; otherwise, an LJMP instruction is placed in the vector table; otherwise an LJMP instruction is placed in the vector table to point to the address of the ISR. Enabling and disabling the interrupts: Each of the interrupt sources can be individually enabled or disabled by setting or clearing a bit in interrupt enable (IE) register. Upon reset, all interrupts are disabled. To enable the interrupt, steps are1) Bit D7 of IE i.e. EA must be set high to enable interrupts. 2) If the corresponding bits of IE are high, then the corresponding interrupts are enabled. Interrupt Enable (IE) Register D7 EA D6 D5 ET2 D4 ES D3 ET1 D2 EX1 D1 ET0 D0 EX0
o D7 - EA:o o o o o o o D6 D5 D4 D3 D2 D1 D0
EA = 0 no interrupt is acknowledged EA = 1 all interrupts are enable Not implemented, reserved for further use Enable or disable timer 2 overflow interrupt. Serial communication interrupt. Timer 1 overflow interrupt. External interrupt 1. Timer 0 interrupt. External interrupt 0.
Timer Interrupts: The timer flag (TF) is raised when the timer rolls over and it is monitored with the instruction JNB TFx, target. In delay generation using polling method, we have to wait until the TF is raised. The problem with this method is that the microcontroller is tied down while waiting for TF to be raised and cannot do any thing else. Using interrupts solves this problem and avoids tying down the controller. If the timer interrupt in the IE register is enabled, whenever the timer overflows, TF is raised, and the microcontroller is interrupted in whatever it is doing and jumps to the interrupt vector table to the service the ISR of timer. In the ISR of the timer, notice that there is no need for
Users Lab Manual (Experiments) clearing the TF before the RETI instruction. This is because the 8051 clears the TF flag internally upon jumping to the interrupt vector table. External Hardware Interrupts: There are only two external hardware interrupts in the 8051 : INT0 and INT1. They are enabled and disabled using IE register bit IE.0 and IE.2. There are two types of activation for the external hardware interrupts 1. Level triggered 2. Edge triggered Level triggered interrupt: In the level triggered mode, INT0 and INT1 pins are normally high and if the low level signal is applied to them, it triggers the interrupt. Then the microcontroller stops whatever it is doing and jumps to the IVT to service the interrupt. This is called a level triggered or level activated interrupt and is the default mode upon reset of the 8051. The low level signal must be removed before the execution of the last instruction of the interrupt service routine, RETI; otherwise, another interrupt will be generated. In other words, if the low-level interrupt signal is not removed before the ISR is finished it is interpreted as another interrupt and the 8051 jumps to the IVT to execute the ISR again. Pins P3.2 and P3.3 are used for normal I/O unless the INT0 and INT1 bits in the IE register are enabled. After the hardware interrupts in the IE register enabled, the controller keeps sampling the INT pin for a low-level signal once each machine cycle. To ensure the activation of the hardware interrupt at the INT pin, make sure that the duration of low level signal is around the 4 machine cycles, but no more. This is due to that the level triggered interrupt is not latched. Thus the pin must be held in a low state until the start of the ISR execution. Edge triggered interrupts: When a high to low signal is applied to pin P3.2 or P3.3, the controller will be interrupted and forced to jump to IVT to service the ISR of the external hardware interrupt. This is called an edge triggered interrupt. Upon reset, 8051 make INT0 and INT1 as low level triggered interrupt. To make edge triggered, we must program the bits of Timer control (TCON) register. The TCON register holds, among other bits, the IT0 and IT1 flag bits that determine level or edge triggered mode of the hardware interrupts. IT0 and IT1 are also referred as TCON.0 and TCON.2 since the TCON is bit addressable. Upon reset, TCON.0 (IT0) and TCON.2 (IT1) are both zeros, meaning that the external hardware interrupts are low level triggered. By making these bits high with instructions such as
Users Lab Manual (Experiments) SETB TCON.0 and SETB TCON.2, the external hardware interrupts become edge triggered. Timer Control (TCON) Register D6 D5 D4 D3 D2 D1 TR1 TF0 TR0 IE1 IT1 IE0
D7 TF1
D0 IT0
o IE1 and IE0: external interrupt edge flag Set by CPU when edge is detected of external interrupt. Cleared by CPU when edge is processed. This flag does not latch low level triggered interrupts. o IT1 and IT0: interrupt 1 type control bit Set to 1 to specify falling edge triggered external interrupt. Clear to 0 to specify low level triggered external interrupt. In edge triggered interrupts, the external the external source must be held high for at least one machine cycle and then held low for at least one machine cycle to ensure that the transition is seen by the microcontroller. The falling edge is latched by the 8051 and is held by the TCON register. The TCON.1 (IE0) and TCON.3 (IE1) bits hold the latched falling edge of pins INT0 and INT1, respectively. IE0 and IE1 function as interrupt in service flags. When and interrupt in service flag is raised, it indicates to the external world that the interrupt is being serviced and no new interrupt on this INT pin will be responded to until this service is finished.
Interrupt priority:
When the 8051 is powered up, the priorities are assigned according to table 4.1. In reality the priority scheme is nothing but an internal polling sequence in which the 8051 polls the interrupts in the sequence listed in table 4.1 and responds accordingly. Highest to lowest priority External interrupt 0 INT0 Timer interrupt 0 TF0 External interrupt 1 INT1 Timer interrupt 1 TF1 Serial communication RI + TI Table 4.1: Interrupt priority on reset
Users Lab Manual (Experiments) We can alter the sequence of table 4.1 by assigning a higher priority to any one of the interrupts. This is done by programming a register called IP (Interrupt Priority Register) which is shown below. Upon the power on reset, the IP register contains all 0s, making the priority based on table 4.1. To give a higher priority to any of the interrupts, we make the corresponding bit in the IP register high. Interrupt Priority (IP) Register D6 D5 D4 D3 D2 D1 -PT2 PS PT1 PX1 PT0
D7 --
D0 PX0
Priority bit = 1 assigns high priority. Priority bit = 0 assigns low priority. PT2 (IP.5) PS (IP.4) PT1 (IP.3) PX1 (IP.2) PT0 (IP.1) PX0 (IP.0) : : : : : : Timer 2 interrupt Priority bit (8052 only) Serial port interrupt Priority bit Timer 1 interrupt Priority bit External interrupt priority bit Timer 0 interrupt Priority bit External interrupt Priority bit
Nested Interrupts:
What happens if the 8051 is executing an ISR belonging to an interrupt and another interrupt is activated? In such cases, a priority interrupt can interrupt a low-level interrupt. This is called as nested interrupts or interrupts inside an interrupt. In the 8051 a low priority interrupt can be interrupted by higher priority interrupt, but not by another low-priority interrupt. Although all the interrupts are latched and kept internally, no low-priority interrupt can get the immediate attention of the CPU until the 8051 has finished servicing the high priority interrupts.
REFERENCES : 1. The 8051 Microcontroller & Embedded systems - M. Mazidi 2. The 8051 Microcontroller Architecture, Programming & Applications - Kenneth Ayala 3. Lab Manual for Universal Microcontroller Development Board, S2N Systems, Pune.
4A) Write a program in which falling edge of pulse is detected by interrupt port pin P3.3 (INT1). In response to this LED, which is connected to port P1.3, is turned on it stay on for 50ms and then turned off.
ORG 0000H SJMP START ORG 0013H SETB P1.3 ACALL DEL_50ms CLR P1.3 RETI ORG 0030H START: SETB TCON.2 MOV IE, #10000100B HERE: SJMP HERE DEL_50ms: MOV R1, #100 LOOP1: MOV R2, #231 LOOP2: DJNZ R2, LOOP2 DJNZ R1, LOOP1 RET END ; ; ; ; ; ; ; ; ; ; ; Skip the interrupt vector ISR address of External Interrupt 1 Turn on the LED keep LED on for 50ms Turn off the LED after delay Return from interrupt make INT1 edge triggered Enable external interrupt 1 loop continuously generates delay of 50ms generates delay of 500us
4B) Write a program to interface LED to P2.0 and toggle it after every 20ms. (Use Timer for delay and interrupts)
ORG 0000H SJMP MAIN ORG 001BH ; TIMER 1 ISR ADDRESS CPL P2.0 ; TOGGLE THE BIT P2.0 MOV TMOD, #10H ; TIMER 1 ISR MOV TL1,#0FFH ; TO GENERATE 50% DUTY CYCLE MOV TH1,#0DBH ; TO GENERATE 50% DUTY CYCLE RETI MOV TMOD,#0001000B; TIMER IN MOD - 1 MOV TL1, #0FFH ; TO GENERATE 50% DUTY CYCLE MOV TH1, #0DBH ; TO GENERATE 50% DUTY CYCLE MOV IE, #10001000B ; ENABLE INTERRUPT SETB TR1 ; START THE TIMER SJMP HERE END
MAIN:
HERE:
4C) Write a program to interface LEDs to 8051 so that a rolling display is observed on the LEDs connected to port P1 (Use Timer for delay).
ORG 0000H LJMP START ORG 0030H START: AGAIN: MOV A, #0FEH MOV P1, A ACALL DELAY ACALL DELAY ACALL DELAY RR A SJMP AGAIN MOV TMOD, #10H MOV TH1, #0H MOV TL1, #0H SETB TR1 JNB TF1, BACK CLR TR1 CLR TF1 RET END
; ROTATE BITS OF A ONE BIT RIGHT ; REPEAT STEPS ; SELECT TIMER 1 MODE 1 ; LOAD COUNT TO GET REQD. DELAY ; START TIMER ; CHECK IF
DELAY:
BACK: OCCURED
OVERFLOW
HAS
PROBLEM DEFINITION: A. Write a program for the 8051 to transfer letter A serially at 4800-baud rate, 8 bit data, 1 stop bit continuously (Show TH value calculation for the given baud). B. Write a program for the 8051 to transfer the message CWIT, PUNE serially at 9600 baud, 8 bit data, 1 stop bit continuously (Show TH value calculation for the given baud).
1. 2. 3. 4.
Keil uVision2 Compiler / Assembler Flashmagic Software for downloading 8051 Trainer kit Hyperterminal
2. Half duplex communication link: In half duplex, the communication link can be used for either transmission or reception. Data is transmitted in only one direction at a time. 3. Full duplex communication link: If the data is transmitted in both ways at the same time, it is a full duplex i.e. transmission and reception can proceed simultaneously. This communication link requires two wires for data, one for transmission and one for reception. Types of Serial communication: Serial data communication uses two types of communication. 1. Synchronous serial data communication: In this transmitter and receiver are synchronized. It uses a common clack to synchronize the receiver and the transmitter. First the synch character is sent and then the data is transmitted. This format is generally used for high speed transmission. In Synchronous serial data communication a block of data is transmitted at a time. 2. Asynchronous Serial data transmission: In this, different clock sources are used for transmitter and receiver. In this mode, data is transmitted with start and stop bits. A transmission begins with start bit, followed by data and then stop bit. For error checking purpose parity bit is included just prior to stop bit. In Asynchronous serial data communication a single byte is transmitted at a time. Baud rate: The rate at which the bits are transmitted is called baud or transfer rate. The baud rate is the reciprocal of the time to send one bit. In asynchronous transmission, baud rate is not equal to number of bits per second. This is because; each byte is preceded by a start bit and followed by parity and stop bit. For example, in synchronous transmission, if data is transmitted with 9600 baud, it means that 9600 bits are transmitted in one second. For bit transmission time = 1 second/ 9600 = 0.104 ms. RS-232 standards: To allow compatibility among data communication equipment made by various manufactures, an interfacing standard called Rs232 was set by the Electronics Industries Association (EIA) in 1960. In 1963 it was modified and called RS232A. RS232B and RS232C were issued in 1965 and 1969, respectively. Today Rs232is the most widely used serial I/O interfacing standard. This standard is used in PCs and numerous equipments. However, since the standard was set long before the advent of logic family, its input and output voltage levels are not TTL compatible. S2N Systems, Pune. Cell No. 9011097672
Users Lab Manual (Experiments) In RS232, a logic one (1) is represented by -3 to -25V and referred as MARK while logic zero (0) is represented by +3 to +25V and referred as SPACE. For this reason to connect any RS232 to a microcontroller system we must use voltage converters such as MAX232 to convert the TTL logic level to RS232 voltage levels and vice-versa. MAX232 IC chips are commonly referred as line drivers. Serial Data Format The serial data format includes one start bit, between five and eight data bits, and one stop bit. A parity bit and an additional stop bit might be included in the format as well. The figure 4.1 below illustrates the serial data format.
Figure 5.1: Serial data format The format for serial port data is often expressed using the following notation: Number of data bits - parity type - number of stop bits. For example, 8-N-1 is interpreted as eight data bits, no parity bit, and one stop bit, while 7-E-2 is interpreted as seven data bits, even parity, and two stop bits. The data bits are often referred to as a character because these bits usually represent an ASCII character. The remaining bits are called framing bits because they frame the data bits.
Users Lab Manual (Experiments) DB-25 Pin No. Pin 2 Pin 3 Pin 4 Pin 5 Pin 6 Pin 7 Pin 8 Pin 20 DB-9 Pin No. Pin 3 Pin 2 Pin 7 Pin 8 Pin 6 Pin 5 Pin 1 Pin 4 Abbreviation Full Name TD RD RTS CTS DSR SG CD DTR Transmit Data Receive Data Request To Send Clear To Send Data Set Ready Signal Ground Carrier Detect Data Ready Terminal
Pin 22 Pin 9 RI Ring Indicator Table 4.2: D Type 9 Pin and D Type 25 Pin Connectors Pin Functions Abbreviation TD RD CTS DCD Full Name Transmit Data Receive Data Clear to Send Data Carrier Detect Function Serial Data Output (TXD) Serial Data Input (RXD) This line indicates that the Modem is ready to exchange data. When the modem detects a "Carrier" from the modem at the other end of the phone line, this Line becomes active. This tells the UART that the modem is ready to establish a link. This is the opposite to DSR. This tells the Modem that the UART is ready to link.
DSR
DTR
RTS
Request To Send This line informs the Modem that the UART is ready to exchange data. Ring Indicator Goes active when modem detects a ringing signal from the PSTN.
RI
Users Lab Manual (Experiments) The 8051 has two pins that are used specifically for transferring and receiving data serially. These two pins are called TXD, RXD and are part of the port 3 group. Pin 11 of the 8051 (P3.1) assigned to TXD and pin 10 (P3.0) is designated as RXD. These pins TTL compatible; therefore they require line driver to make them RS232 compatible. One example of such a converter is MAX232 from Maxim Corporation which converts from RS232 voltage levels to TTL voltage levels and vice versa. One advantage of the MAX232 is that it uses a +5V power source which is the same as the source voltage for the 8051.
VCC C8 U3 C9 1 uF TXD RXD 1 3 4 5 11 12 10 9 C1+ C1C2+ C2T1IN R1OUT T2IN R2OUT MAX232N 16 1 uF C10 VS+ VSGND T1OUT R1IN R2IN T2OUT 2 6 15 14 13 8 7 1 uF C11 1 uF 1 6 2 7 3 8 4 9 5 D Connector 9 C12 1 uF J8
8051 serial communication: The 8051 supports a full duplex serial port. The 8051 transfers and receives the data serially with different baud rate. Three special function registers support serial communication, namely, SBUF register, SCON register, PCON register. 1. SBUF Register: serial buffer (SBUF) register is an 8-bit register. It has separate SBUF registers for data transmission and for data reception. These two registers are accessed by the same name, SBUF. One of the registers is write-only and used to hold data to transmit via TXD pin. The other is read only and holds the received data from external source via RXD pin. For a byte of data to be transferred via the TXD line, it must be placed in SBUF register. Similarly, SBUF holds the 8-bit data received by the RXD pin and read to accept the received data. 2. SCON register: The contents of the Serial Control (SCON) register are shown below. This register contains mode selection bits, serial port interrupt bit (TI and RI) and also the ninth data bit for transmission and reception (TB8 and RB8). 3. PCON register: The SMOD bit (bit 7) of PCON register controls the baud rate in asynchronous mode transmission. S2N Systems, Pune. Cell No. 9011097672
VCC
Serial Port Control (SCON) Register D7 SM0 D6 SM1 D5 D4 SM2 REN D3 TB8 D2 RB8 D1 TI D0 RI
o SM0 (SCON.7) : Serial communication mode selection bit o SM1 (SCON.6) : Serial communication mode selection bit SM0 0 0 1 1 SM1 0 1 0 1 Mode Mode 0 Mode 1 Mode 2 Mode 3 Description 8-bit shift mode 8-bit UART 9-bit UART 9-bit UART Baud rate register Fosc / 12 Variable (set by timer 1) Fosc/ 32 or Fosc/64 Variable (set by timer 1)
o SM2 (SCON.5) : Multiprocessor communication bit. In modes 2 and 3, if set this will enable multiprocessor communication. o REN (SCON.4) : Enable serial reception o TB8 (SCON.3) : This is 9th bit that is transmitted in mode 2 & 3. o RB8 (SCON.2) : 9th data bit is received in modes 2 & 3. o TI (SCON.1) : Transmit interrupt flag, set by hardware must be cleared by software. o RI (SCON.0) : Receive interrupt flag, set by hardware must be cleared by software.
Power mode Control (PCON) Register D7 D6 SMOD -D5 -D4 -D3 GF1 D2 GF0 D1 PD D0 IDL
o SMD (PCON.7) : Serial rate modify bit. Set to 1 by program to double baud rate using timer 1 for modes 1, 2, and 3. cleared by program to use timer 1 baud rate. o GF1 (PCON.3) : General Purpose user flag bit. o GF0 (PCON.2) : General Purpose user flag bit. o PD (PCON.1) : Power down bit. Set to 1 by program to enter power down configuration for CHMOS processors. o IDL (PCON.0) : Idle mode bit. Set to 1 by program to enter idle mode configuration for CHMOS processors.
REFERENCES
1. The 8051 Microcontroller & Embedded systems - M. Mazidi 2. The 8051 Microcontroller Architecture, Programming & Applications - Kenneth Ayala 3. Lab Manual for Universal Microcontroller Development Board, S2N Systems, Pune.
PROBLEM DEFINITION: A. Draw the complete interfacing diagram of ADC 808 to 8051 and explain the pin connections in the figure. B. Write a program to interface ADC 808 to 8051. Apply the analog input and get the corresponding digital output. Write the result in a tabular form. S/W & H/W USED : 1. 2. 3. 4. Keil uVision2 Simulator Software, Flashmagic Software for downloading 8051 Trainer kit ADC 808 interfacing card
THEORY:
ADC Devices: Analog to digital converters are among the most widely used devices for data acquisitions. Digital computers use binary (discrete) value but in physical world everything is analog (continuous). A physical quantity is converted to electrical signals using device called transducer or also called as sensors. Sensors and many other natural quantities produce an output that is voltage (or current). There fore we need an analog - to - digital converter to translate the analog signal to digital numbers so that the microcontroller can read and process them. An ADC has an n bit resolution where n can be 8, 10, 16, 0r even 24 bits. The higher resolution ADC provides a smaller step size, where step size is smallest change that can be discerned by an ADC. This is shown in Table 6.1. In addition to resolution, conversion time is another major factor in judging an ADC. Conversion time is defined as the time it takes the ADC to convert the analog input to digital (binary) number. The ADC chips are either parallel or serial. In parallel ADC, we have 8 or more pins dedicated to bring out the binary data, but in serial ADC we have only one pin for data out.
Users Lab Manual (Experiments) n - bit Number of steps 8 256 10 1024 12 4096 16 65536 Table 6.1: Resolution verses Step Size (mV) 5/256 = 19.53 5/1024 = 4.88 5/4096 = 1.2 5/65536 = 0.076 step size for ADC.
ADC 0808 chip with analog channels ADC0808, from national semiconductors, has 8 analog inputs. ADC0808 allows us to monitor up to 8 different analog inputs using only a single chip. ADC0808 has an 8-bit data output. The 8 analog inputs channels are multiplexed and selected according to table given below using three address pins, A, B, and C. In ADC0808 Vref (+) and Vref (-) set the reference voltage. If Vref (-) = Gnd and Vref (+) = 5V, the step size is 5V/ 256 = 19.53 mV. Therefore, to get a 10 mV step size we need to set Vref (+) = 2.56V and Vref(-) = Gnd. From figure natice ALE pin. We use A, B, and C addresses to select IN0 IN7, and activate ALE to latch in the address. SC for start conversion. EOC is for end-of-conversion, and OE is for output enable (READ). Table shows the step size relation to the Vref Voltage. Select Analog Channel C B A IN0 0 0 0 IN1 0 0 1 IN2 0 1 0 IN3 0 1 1 IN4 1 0 0 IN5 1 0 1 IN6 1 1 0 IN7 1 1 1 Table 6.2: ADC0808 analog channel selection. Vref (v) Vin (V) Step Size (mV) 5/256 = 19.53 4/256 = 15.32 3/256 = 11.71 2.56/256 = 10 2/256 = 7.81 1/ 256 = 3.90 range for ADC 0808
Not connected 0 to 5 4.0 0 to 4 3.0 0 to 3 2.56 0 to 2.56 2.0 0 to 2 1 0 to 1 Table 6.3: Vref relation to Vin Timing Diagram
Figure 6.2: ADC0808 interfaced to 8051 Steps to program the ADC0808 The following are steps to get data from an ADC0808. S2N Systems, Pune. Cell No. 9011097672
Users Lab Manual (Experiments) 1. Select an analog channel by providing bits to A, B, and C addresses according to table. 2. Activate the ALE (address latch enable) pin. It needs an L-to-H pulse to latch in the address. 3. Activate SC (start conversion) by an L-to-H pulse to initiate conversion. 4. Monitor EOC (end of conversion) to see whether conversion is finished. H-to-l output indicates that data is converted and ready to be picked up. 5. Activate OE (output enable) to read data out of ADC chip. An L-to-H pulse to the OE pin will bring digital data out of the chip. Also notice that the OE is the same as the RD pin in other ADC chip. Notice that in ADC0808 there is no self-clocking and the clock must be provided from an external source to the CLK pin. Although the speed of conversion depends on the frequency of the clock connected to the CLK pin, it cannot be faster than 100 microseconds.
REFERENCES
1. The 8051 Microcontroller & Embedded systems - M. Mazidi 2. The 8051 Microcontroller Architecture, Programming & Applications - Kenneth Ayala 3. Lab Manual for Universal Microcontroller Development Board, S2N Systems, Pune.
6A) Write a program to interface ADC 808 to 8051. Apply the analog input and get the corresponding digital output. Write the result in a tabular form.
; System description CHA CHB CHC ALE START OE EOC ADCOP EQU EQU EQU EQU EQU EQU EQU EQU P2.0 P2.1 P2.2 P0.2 P0.1 P0.0 P0.4 P3
ORG 0000H SJMP MAIN ORG 0030H MOV P3,#0FFH MOV P0,#0F0H SETB CHA CLR CHB CLR CHC CLR ALE NOP SETB ALE NOP CLR ALE CLR START NOP SETB START NOP CLR START JNB EOC,CHECK SETB OE MOV A, ADCOP MOV P1,A CLR OE SJMP BACK END
MAIN: BACK:
; Port 3 as input port ; Higher nibble of Port 0 as input port ; Select IN1 as input source
CHECK:
; ; : ;
Check for end of conversion Set the output enable Get digital data output in Accumulator Show the result on LEDs
PROBLEM DEFINITION: A. Draw the interfacing diagram of DAC 808 and explain all the pin connections in the figure. B. Write a program to interface DAC 808 to 8051. Apply the digital input and get the corresponding square wave output. C. Write a program to interface DAC 808 to 8051. Apply the digital input and get the corresponding triangular wave output. S/W & H/W USED : 1. 2. 3. 4. Keil uVision2 Simulator Software, Flashmagic Software for downloading 8051 Trainer kit DAC 808 interfacing card
THEORY:
Digital-to-analog (DAC) converter: The digital to analog converter (DAC) is a widely used to convert digital pulses to analog signals. There two methods of creating DAC: 1. binary weighted, 2. R/2R ladder. The vast majority of integrated circuit DACs use the R/2R method since it can achieve a much higher degree of precision. The first criterion judging a DAC is its resolution, which is a nfunction of the number of binary inputs. The common ones are 8, 10 and 12 bits. The number of data bit inputs decides the resolution of the DAC since the number of analog output levels is equal to 2n, where n is the number of data bit inputs. Therefore, an 8-bit input DAC such as the DAC0808 provides 256 discrete voltage (or current) levels of output. Similarly, the 12-bit DAC provides 4096 discrete voltage levels.
Users Lab Manual (Experiments) In the DAC 0808, the digital inputs are converted to current (I out), and by connecting a register to the I out pin, we convert the result to voltage. The total current provided by the I out pin is a function of the binary numbers at then D0 D7 inputs of the DAC0808 and the reference current (I out), and is as fallows:
D 7 D 6 D5 D 4 D3 D 2 D1 D 0 I out = I ref + + + + + + + 4 8 16 32 64 128 256 2
Where D0 is the LSB, D7 is the MSB for the inputs, and I ref is the input current that must be applied to pin 14. The Iref current is generally set to 2.0 mA. Figure shows the generation of current reference (setting Iref = 2mA) by using the standard 5-V power supply and 1K and 1.5K- ohm standard resistors. Now assuming that Iref = 2mA, if all the inputs to the DACare high, the maximum output current is 1.99mA. Converting I
out
to voltage in DAC0808
Ideally we connect the output pin Iout to a resistor, convert this current to voltage, and monitor the output on scope. In real life, however this can cause inaccuracy since the input resistance of the load where it is connected will also affect the output voltage. For this reason, the Iref current output is isolated by connecting it to an op-amp such as 741 with Rf = 5K ohms for the feedback resistor. Assuming that R= 5K ohms, by changing the binary input, the output voltage changes as shown in below program CLR A AGAIN: MOV P1, A ; send data to DAC INC A ; count from 0 to ffh ACALL DELAY ; let DAC recover SJMP AGAIN
REFERENCES
1. The 8051 Microcontroller & Embedded systems - M. Mazidi 2. The 8051 Microcontroller Architecture, Programming & Applications - Kenneth Ayala 3. Lab Manual for Universal Microcontroller Development Board, S2N Systems, Pune.
7A) Write a program to interface DAC 808 to 8051. Apply the digital input and get the corresponding square wave output.
ORG 0000H SJMP START ORG 0030H MOV A, #0 MOV P2, A ACALL DELAY CPL A SJMP BACK MOV R2, #0FFH DJNZ R2, HERE RET END
START: BACK:
DELAY: HERE:
7B) Write a program to interface DAC 808 to 8051. Apply the digital input and get the corresponding triangular wave output.
ORG 0000H SJMP START ORG 0030H MOV A, #0FFH INC A MOV P2, A CJNE A, #0FFH, BACK1 DEC A MOV P2, A CJNE A, #00H, BACK2
START: BACK1:
BACK2:
PROBLEM DEFINITION: A. Draw the complete interfacing diagram of stepper motor and explain all the pin connections in the figure. B. Write a program to interface stepper motor to 8051 and rotate it through clock-wise / anti clockwise direction continuously. C. Write a program to interface stepper motor to 8051 and rotate it through clock-wise / anti clockwise direction through 1800. S/W & H/W USED : 1. 2. 3. 4. Keil uVision2 Simulator Software, Flashmagic Software for downloading 8051 Trainer kit Stepper motor interfacing card
THEORY:
A stepper motor is a widely used device that translates electrical pulses into mechanical movement. In applications such as disk drives, dot matrix printers, and robotics, the stepper motor is used for position control. Stepper motors commonly have a permanent magnet rotor (also called the shaft) surrounded by a stator (see Figure 8.1). There are also steppers called variable reluctance stepper motors that do not have a PM rotor. The most common stepper motors have four stator windings that are paired with a center-tapped common as shown in Figure 8.2. This type of stepper motor is commonly referred to as a four-phase or unipolar stepper motor. The center tap allows a change of current direction in each of two coils when a winding is grounded, thereby resulting in a polarity change of the stator.
Figure 8.2: Stator windings configuration Notice that while a conventional motor shaft runs freely, the stepper motor shaft moves in a fixed repeatable increment, which allows one to move it to a precise position. This repeatable fixed movement is possible as a result of basic magnetic theory where poles of the same polarity repel and opposite poles attract. The direction of the rotation is dictated by the stator poles. The stator poles are determined by the current sent through the wire coils. As the direction of the current is changed, the polarity is also changed causing the reverse motion of the rotor. The stepper motor discussed here has a total of 6 leads: 4 leads representing the four stator windings and 2 commons for the centertapped leads. As the sequence of power is applied to each stator winding, the rotor will rotate. There are several widely used sequences where each has a different degree of precision. Table 8.1 shows a 2-phase, 4-step stepping sequence.
Users Lab Manual (Experiments) clockwise Step Winding Winding Winding Winding Counter # A B C D clockwise 1 1 0 0 1 2 1 1 0 0 3 0 1 1 0 4 0 0 1 1 Table 8.1: Normal 4-step Sequence It must be noted that although we can start with any of the sequences in Table 8.1, once we start we must continue in the proper order. For example, if we start with step 3 (0110), we must continue in the sequence of steps 4, 1, 2, etc. STEP ANGLE: How much movement is associated with a single step? This depends on the internal construction of the motor, in particular the number of teeth on the stator and the rotor. The step angle is the minimum degree of rotation associated with a single step. Various motors have different step angles. Table 8.2 shows some step angles for various motors. In table 8.4, notice the term steps per revolution. This is the total number of steps needed to rotate one complete rotation or 360 degrees (e. g., 180 steps * 2 degrees =360). It must be noted that perhaps contrary to ones initial impression, a stepper motor does not need more terminal leads for the stator to achieve smaller steps. All the stepper motors discussed in this section have 4 leads for the stator winding and 2 COM wires for the center tap. Although some manufacturers set aside only one lead for the common signal instead of two, they always have 4 leads for the stators. Next we discuss some associated terminology in order to understand the stepper motor further. Step angle Steps per revolution 0.72 500 1.8 200 2.0 180 2.5 144 5.0 72 7.5 48 15 24 Table 8.2: Stepper motor step angles
Users Lab Manual (Experiments) STEPS PER SECOND AND RPM RELATION The relation between rpm (revolutions per minute), steps per revolution, and steps per second is as follows.
The four-step sequence and number of teeth on rotor The switching sequence shown earlier in Table 8.1 is called the 4step switching sequence since after four steps the same two winding will be ON. How much movement is associated with these four steps? After completing every four steps, the rotor moves only one tooth pitch. Therefore, in a stepper motor with 200 steps per revolution, the rotor has 50 teeth since 4x 50 =200 steps are needed to complete one revolution. This leads to the conclusion that the minimum step angle is always a function of the number of teeth on the rotor. In other words, the smaller the step angle, the more teeth the rotor passes. One might wonder what happens if we want to move 45 degrees, since the steps are 2 degrees each. To allow for finer resolution, all stepper motor allows what is called an 8- step sequence. The 8-step sequence is also called half-stepping, since in the 8-step sequence each step is half of the normal step angle. For example, a motor with a 2-degree step angle can be used as a 1degree step angle if the sequence of Table 8.3 is applied. clockwise Step Winding Winding Winding Winding Counter # A B C D clockwise 1 1 0 0 1 2 1 0 0 0 3 1 1 0 0 4 0 1 0 0 5 0 1 1 0 6 0 0 1 0 7 0 0 1 1 8 0 0 0 1 Table 8.3: Half-step 8-step Sequence Motor speed The motor speed, measured in steps per second (steps/s), is a function of the switching rate. By changing the length of the time delay loop in the program, we can achieve various rotation speeds. Holding torque The fallowing is a definition of holding torque: with the motor shaft at standstill or zero rpm condition, the amount of torque, from an external source, required to break away the shaft from its holding S2N Systems, Pune. Cell No. 9011097672
Users Lab Manual (Experiments) position. This is measured with rated voltage and current applied to the motor. The unit of torque is ounce-inch (or kg-cm). Wave drive 4-step sequence In addition to the 8-step and 4-step sequences discussed earlier, there is another sequence called the wave drive 4-step sequence. It is shown in table 8.3 is simply the combination of the wave drive 4step and normal 4-step sequences shown in Table 8.4 and 8.1, respectively. Experimenting with the wave drive 4-step is left to the reader. clockwise Step Winding Winding # A B 1 1 0 2 0 1 3 0 0 4 0 0 Table 8.4: Wave Drive Winding Winding Counter C D clockwise 0 0 0 0 1 0 0 1 4-Step Sequence
c) Bipolar
Users Lab Manual (Experiments) Unipolar stepper motor can be controlled using the basic interfacing shown in Figure 8.4, whereas the bipolar stepper requires H-Bridge circuitry. Bipolar stepper motor require a higher operational current than the unipolar, the advantage of this is a higher holding torque.
Using transistors as drivers: Figure 8.4 shows an interface to a unipolar stepper motor using transistors. Diodes are used to reduce the back EMF spike created when the coils are energized and de-energized, similar to the electromechanical relays discussed earlier.
VCC W_A COM VCC W_B VCC W_C COM W_D Stepper Motor
P0.0
P0.1
8051 uc
P0.2
VCC
P0.3
1. The 8051 Microcontroller & Embedded systems - M. Mazidi 2. The 8051 Microcontroller Architecture, Programming & Applications - Kenneth Ayala 3. Lab Manual for Universal Microcontroller Development Board, S2N Systems, Pune.
8A) Write a program to interface stepper motor to 8051 and rotate it through clock-wise / anti clockwise direction continuously
ORG 0000H LJMP START ORG 0030H START: MOV P0, #0AH ACALL DELAY MOV P0, #06H ACALL DELAY MOV P0, #05H ACALL DELAY MOV P0, #09H ACALL DELAY SJMP START ; Load the excitation for wdg. C and D ; Load the excitation for wdg. B and C ; Load the excitation for wdg. A and B ; Load the excitation for wdg. A and D ; Skip the interrupt vector table
DELAY:
BACK1:
Note: Anti clock wise direction change the sequence form 0A, 06, 05, 09 to 09, 05, 06, 0A.
8B) Write a program to interface stepper motor to 8051 and rotate it through clock-wise / anti clockwise direction through 1800.
ORG 0000H LJMP START ORG 0030H START: BACK: MOV R2, #25 MOV P0, #0AH ACALL DELAY MOV P0, #06H ACALL DELAY MOV P0, #05H ACALL DELAY MOV P0, #09H ACALL DELAY DJNZ R2, BACK HERE: SJMP HERE ; Load the excitation for wdg. C and D ; Load the excitation for wdg. B and C ; Load the excitation for wdg. A and B ; Load the count for 180 degree roatation ; Load the excitation for wdg. A and D ; Skip the interrupt vector table
DELAY:
BACK1:
Note: Anti clock wise direction change the sequence form 0A, 06, 05, 09 to 09, 05, 06, 0A.
PROBLEM DEFINITION: A. Draw the interfacing diagram of 16x2 LCD to 8051 and explain all the necessary pin connections in the figure. B. Write a program to interface a 16x2 LCD to 8051 and display S-Square-N Sys. on first line and PUNE on second line of the LCD. S/W & H/W USED : 1. 2. 3. 4. Keil uVision2 Simulator Software, Flashmagic Software for downloading 8051 Trainer kit LCD interfacing card
I I/O I/O I/O I/O I/O I/O I/O I/O Backlight Supply -
Cursor home
I/D
Cursor/display shift 0
S/C R/L *
DL
CGRAM address
DDRAM address
BF
0 1
Bit names and abbreviations Bit name Setting / Status I/D 0 = Decrement cursor position 1 = Increment cursor position S 0 = No display shift 1 = Display shift D 0 = Display off 1 = Display on C 0 = Cursor off 1 = Cursor on B 0 = Cursor blink off 1 = Cursor blink on S/C 0 = Move cursor 1 = Shift display R/L 0 = Shift left 1 = Shift right DL 0 = 4-bit interface 1 = 8-bit interface N 0 = 1/8 or 1/11 Duty (1 line) 1 = 1/16 Duty (2 lines) F 0 = 5x7 dots 1 = 5x10 dots BF 0 = Can accept instruction 1 = Internal operation in progress - DDRAM = Display Data RAM. - CGRAM = Character Generator RAM. - DDRAM address corresponds to cursor position. - * = Don't care. 8-bit Interface of LCD
Sr. No. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17
Command to LCD instruction Clear display screen Return home Decrement cursor (shift cursor to left) Increment cursor (shift cursor to right) Shift display right Shift display left Display off, cursor off Display off, cursor on Display on, cursor off Display on cursor blinking Shift cursor position to left Shift cursor position to right Shift the entire display to left Shift the entire display to right Force cursor to beginning of 1st line. Force cursor to beginning of 2nd line. 2 lines and 5x7 matrixes.
Code (Hex) 01 02 04 06 05 07 08 0A 0C 0E 10 14 18 1C 80 C0 38
REFERENCES
1. The 8051 Microcontroller & Embedded systems - M. Mazidi 2. The 8051 Microcontroller Architecture, Programming & Applications - Kenneth Ayala 3. Lab Manual for Universal Microcontroller Development Board, S2N Systems, Pune. 9A) Write a program to interface a 16x2 LCD to 8051 and display S-Square-N Sys. on first line and PUNE on second line of the LCD.
EN RW RS LCD_DATA EQU EQU EQU EQU P3.0 P3.1 P3.2 P2
MAIN:
NEXT:
TRANS1:
ORG 0000H SJMP MAIN ORG 0030H MOV A, #38H ; LCD of 2lines, 5x7 matrix, bus - 8bit ACALL CAMMAND ACALL DELAY MOV A, #38H ; repeat above three instructions ACALL CAMMAND ACALL DELAY MOV A, #0EH ; cursor ON, display ON ACALL CAMMAND ACALL DELAY MOV A, #06H ; increment curser pointer ACALL CAMMAND ACALL DELAY MOV A, #01H ; Clear the display ACALL CAMMAND ACALL DELAY MOV A, #80H ; set address of first line. ACALL CAMMAND ACALL DELAY MOV DPTR, #MSG1; Initialize the DPTR with message CLR A MOVC A, @A+DPTR CJNE A, #0FFH, TRANS1 SJMP SKIP1 ACALL DATA_WRITE ; write on LCD ACALL DELAY INC DPTR ; Next character SJMP NEXT MOV A, #0C0H ACALL CAMMAND ; set address of second line.
SKIP1:
NEXT2:
TRANS2:
SKIP2:
CAMMAND: MOV P2, A; PUT DATA IN TO PORT 2.0 CLR RS; R0=0 FOR COMMAND CLR RW; RW=0 WRITE OPERATION SETB EN; FOT LOW TO HIGH PULSE ACALL DELAY NOP NOP CLR EN RET DATA_WRITE: MOV P2,A SETB RS CLR RW SETB EN ACALL DELAY NOP NOP CLR EN RET
MOV R3, #50 MOV R4, #255 DJNZ R4, HERE2 DJNZ R3, HERE1 RET
PROBLEM DEFINITION:
A.
Draw the interfacing diagram of 4x4 keypad to 8051 and explain all the necessary pin connections in the figure.
B.
Write a program to interface 4x4 keypad to 8051 and display the key pressed on the LED.
C.
Write a program to interface 4x4 keypad to 8051 and display the key pressed on the 7-segment Display.
1. 2. 3. 4. 5.
Keil uVision2 Simulator Software, Flashmagic Software for downloading 8051 Trainer kit Keypad interfacing card 7- Segment interfacing card
Users Lab Manual (Experiments) Figure shows a 4 x 4 matrix connected to port 0 of the 8051. The lower nibble (P0.0 to P0.3) is acting as input port and the higher nibble (P0.4 to P0.7) is acting as output port. The rows (scan lines) are connected to an output port and the columns (return lines) are connected to an input port. If no key has been pressed, the input port will yield 1s for all columns since they are all connected to high (Vcc). If all the rows are grounded and a key is pressed, one of the columns will have 0 since the key pressed provides the path to ground. It is the function of the microcontroller to scan the keyboard continuously to detect and identify the key pressed. How it is done is explained next.
Users Lab Manual (Experiments) that the first key press detection was not an erroneous one due to a spike noise, and (b) the 20 ms delay prevents the same key press from being interpreted as a multiple key press. If after 20-ms delay the key is still pressed, it goes tot the next stage to detect which row it belongs to; otherwise, it goes back into the loop to detect a real key press.
VCC
8051 uc P0.3
P0.4 P0.5 P0.6 P0.7
Figure 10.1: Matrix Keyboard connection Port 0 3. To detect which row the key press belongs to, the microcontroller grounds one row at a time, reading the columns each time. If it finds that all columns are high, this means that the key press cannot belong to that row; therefore, it grounds the next row and continues until it finds the row the key press belongs to. Upon finding the row that the key press belongs to, it sets up the starting address for the look-up table holding the scan codes (or the ASCII value) for that row and goes to the next stage to identify the key 4. To identify the key press, the microcontroller rotates the column bits, one bit at a time, into the carry flag and checks to see if it is low. Upon finding the zero, it pulls out the ASCII code for that key from the look-up table; otherwise, it increments the pointer to the next element of the look-up table. Figure 12-7 flowcharts this process. While the key press detection is standard for all keyboards, the process for determining which key is pressed varies. The look-up table method shown in Program can be modified to work with any matrix up to 8 x 8 matrix. S2N Systems, Pune. Cell No. 9011097672
REFERENCES
1. The 8051 Microcontroller & Embedded systems - M. Mazidi 2. The 8051 Microcontroller Architecture, Programming & Applications - Kenneth Ayala 3. Lab Manual for Universal Microcontroller Development Board, S2N Systems, Pune.
10A) Write a program to interface a 4x4 keypad to 8051 and display the key pressed on the LED connected to port 1 (P1).
;SCAN LINES P0.0 TO P0.3 ;RETURN LINES P0.4 TO P0.7 KEYPORT EQU P0 LEDPORT EQU P1 ORG 0000H SJMP MAIN
ORG 0030H MAIN: MOV KEYPORT, #0F0H ; Make return line as input and scan lines zero MOV A, KEYPORT ; Read the return lines ANL A, #0F0H ; Mask the unused bits CJNE A, #0F0H, CHECK1 ; key pressed branch to check1 SJMP MAIN ; branch to main till key pressed CHECK1: ACALL DELAY_20MS ; wait for debounce time MOV A, KEYPORT ; check key closure ANL A, #0F0H ; mask unused bits CJNE A, #0F0H, NEXT ; key pressed baranch to next to find row SJMP MAIN ; branch to main till key pressed NEXT: MOV KEYPORT, #0FEH ; Ground scan line 0 MOV A, KEYPORT ; read the retrun lines ANL A, #0F0H CJNE A, #0F0H, SCAN_R0W0 ; branch if key is in scan line 0 MOV KEYPORT, #0FDH ; Ground scan line 1 MOV A, KEYPORT ; read the retrun lines ANL A, #0F0H CJNE A, #0F0H, SCAN_R0W1 ; branch if key is in scan line 1 MOV KEYPORT, #0FBH ; Ground scan line 2
0 1 2 3
; delay program
; Key code to display on LED's R0W0: DB 0FFH, 0FEH, 0FDH, 0FCH R0W1: DB 0FBH, 0FAH, 0F9H, 0F8H R0W2: DB 0F7H, 0F6H, 0F5H, 0F4H R0W3: DB 0F3H, 0F2H, 0F1H, 0F0H END
; ; ; ;
0 4 8 C
1 5 9 D
2 6 A E
3 7 B F
10B) Write a program to interface a 4x4 keypad to 8051 and display the key pressed on 7-segment display.
;SCAN LINES P0.0 TO P0.3 ;RETURN LINES P0.4 TO P0.7 KEYPORT EQU P0 LEDPORT EQU P1 ORG 0000H SJMP MAIN ORG 0030H MAIN: CLR P3.7 MOV KEYPORT, #0F0H MOV A, KEYPORT ANL A, #0F0H CJNE A, #0F0H, CHECK1 SJMP MAIN CHECK1: ACALL DELAY_20MS MOV A, KEYPORT ANL A, #0F0H CJNE A, #0F0H, NEXT SJMP MAIN
; ; ; ; ; ; ; ; ; ;
Make return line as input and scan lines zero Read the return lines Mask the unused bits key pressed branch to check1 branch to main till key pressed wait for debounce time check key closure mask unused bits key pressed baranch to next to find row branch to main till key pressed
NEXT: MOV KEYPORT, #0FEH ; Ground scan line 0 MOV A, KEYPORT ; read the retrun lines ANL A, #0F0H CJNE A, #0F0H, SCAN_R0W0 ; branch if key is in scan line 0 MOV KEYPORT, #0FDH ; Ground scan line 1 MOV A, KEYPORT ; read the retrun lines ANL A, #0F0H CJNE A, #0F0H, SCAN_R0W1 ; branch if key is in scan line 1 MOV KEYPORT, #0FBH MOV A, KEYPORT ANL A, #0F0H CJNE A, #0F0H, SCAN_R0W2 MOV KEYPORT, #0F7H MOV A, KEYPORT ANL A, #0F0H CJNE A, #0F0H, SCAN_R0W3 SJMP MAIN SCAN_R0W0: MOV DPTR, #R0W0 ; Ground scan line 2 ; read the return lines ; branch if key is in scan line 2 ; Ground scan line 3 ; read the retrun lines ; branch if key is in scan line 3
; Initialise the DPTR with address of Row3 ; rotate left until the zero ; find column and update DPTR
; clear the accumulator ; get the key code ; send the data to P2 to which LED
; delay program
to display key code on 7-segment display 88H, 0EBH, 4CH, 49H ;0 1 2BH, 19H, 18H, 0CBH ;4 5 08H, 09H, 0AH, 38H ;8 9 7CH, 68H, 1CH, 1EH ;C D
2 6 A E
3 7 B F
EXPT. NO. : 11 TITLE : To Study various design and Development Tools for Microcontroller
PROBLEM DEFINITION: Explain the following design and development tools for microcontrollers 1. Assembler 2. Compiler 3. Simulator 4. Emulator 5. Logic analyzer THEORY:
Users Lab Manual (Experiments) object file and list file. The extension for the object file is obj while the extension for the list file is lst. 3. Assemblers require a third step called linking. The link program takes one or more object files and produces an absolute file with the extension abs. This abs file is used by 8051 trainers that have monitor program. 4. Next, the abs file is fed into a program called OH (object to hex converter), which creates a file with extension hex that is ready to burn into ROM. This program comes with all 8051 assemblers. Recent Windows-based assemblers combine steps 2 through 4 into one step.
Figure 1.4: Steps to create program More about .asm and .obj files: The asm file is also called the source file and for this reason some assemblers require that this file have the src extension. Check your
Users Lab Manual (Experiments) 8051 assembler to see which extension it requires. As mentioned earlier, this file is created with an editor such as DOS EDIT or Windows Notepad. The 8051 assembler converts the asm files Assembly language instructions into machine language and provides the obj (object) file. In addition to creating the object file, the assembler also produces the lst (list) file. .LST (list) file: The lst file, which is optional, is very useful to the programmer because it lists all the opcodes and addresses as well as errors that the assembler detected. Many assemblers assume that the list file is not wanted unless you indicate that you want to produce it. This file can be accessed by an editor such as DOS EDIT and displayed on monitor or sent to the printer to produce a hard copy. The programmer uses the list file to find syntax error. It is only after fixing all the errors indicated in the list file that the .obj file is ready to be input to the linker program.
EMULATOR:
Another way to run your program to is with an emulator. An emulator is a mixture of hardware and software. It is used to test and debug the hardware and software of an external system, such as the prototype of a microprocessor based instrument. Part of the hardware of an emulator is a multi-wire cable which connects the host system to the system being developed. A plug at the end of the cable is plugged into the prototype system in place of its microcontroller. Through this connection the software of the emulator allows us to download object program code into RAM in the system being tested and run it. An emulator allows us to load and run programs, examine and change the contents of registers, memory locations and insert the breakpoints in the program. The emulator also takes a snapshot of the contents of registers, activity on the address and data bus and the state of the flags as each instruction executes. The emulator stores this trace data, as it is called, in a large RAM.
Users Lab Manual (Experiments) all tools including C compiler, macro assembler, linker/locator and HEX file generator. vision3 helps the expedite the development process of embedded applications.
Users Lab Manual (Experiments) 2. To create a new project, from PROJECT menu, select NEW PROJECT. The screen should look something like this.
3. The open dialog window will be displayed. Select the desired path where you wish to create this new project. Create new folder for every new project.
Users Lab Manual (Experiments) 4. When you create a new project, Vision3 asks you to select a CPU for the project. The select device dialog box shows the Vision3 device database. Select the microcontroller Philips P89V51RD2.
5. After the Project is created, the screen should look something like this.
6. To create a new source file either .asm or .c, from FILE menu, select NEW. The screen should look something like this.
7. After editing the program in source file, save the source file with .asm extension (it is very must to give extension otherwise file is treated as normal text file.) in project folder.
8. Once the source file is created, add .asm file to your project. You can select the source group in the project workspace and files and click the right mouse key to open a local menu.
9. The option Add files opens the standard files dialog. Select the desired file which is created.
10. After adding the file, go to options for the target to select the proper crystal frequency and Hex file creation. You can select the Target 1 in the project workspace and click the right mouse key to open a local menu.
11. After selecting the options for Target, the screen should look something like this. Then type the desired clock frequency as shown below.
12. To check the options for creating the Hex file go to output tab of options for target window. Then specify the name of Hex file (default is project name) and check the box to create hex file as shown below.
13. To build a project, go to PROJECT Build target, translate all source files and link the application with a click on the Build target toolbar icon. When you build an application with syntax errors, compiler will display errors and warning messages in the output window. A double click on a message line opens the source file on the correct location in editor window.
Users Lab Manual (Experiments) 14. After successful creation .obj file and .hex file go to DEBUG Start/stop debug session to debug / single step the program.
15. After clicking the start debug session, the screen should look something like this. To view the parallel ports, time/counter, interrupt go to Peripherals Menu. To view the memory window, serial window go to View Menu. To single step press F10.
Users Lab Manual (Experiments) Downloading and running user programs Microcontroller P89V51RD2 includes on-chip flash, which is insystem programmable (ISP) for storing user program and non-volatile data. Therefore it is possible to download user program into on-chip flash, through serial port connected to PC. For this purpose software FLASH MAGIC is used. To down load the program using FLASH MAGIC follow the steps as below. 1. Connect the Power supply and keep the board in switched off mode. 2. Connect the RS232 port of trainer kit to COM1 of a PC using serial communication cable. 3. Start the flash magic by START PROGRAMS FLASH MAGIC Flash magic.exe. You will get the screen as below.
4. Do proper settings in flash magic (Device: P89V51RD2, COM port: COM1, Baud rate: 9600, Interface: None (ISP), enable erase block used by the HEX file.
Users Lab Manual (Experiments) 5. Click on Verify after programming to verify the program. 6. Very Important: Do not select set security bit, Fill unused Flash, Gen block checksums, Prog Clocks bit. 7. Once the all settings are completed, select the Hex file which is to be downloaded. 8. Use the browse option to go to the required directory. Click on the hex file you want to download to the target hardware.
9. After selection of the file. Click on the START button. Following message will be displayed. 10. At this point you should power ON the board. If the board is already powered ON, then you should press the reset switch on the board. 11. After the above, the above message will disappear and the programming will start. 12. Finally you will get the message on the bottom of the flash magic screen is finished. 13. To run the program, RESET the board or POWER OFF and POWER ON the board again. REFERENCES: